Vertex* graph_get_vertex(const Graph *g, unsigned long index) { assert(g != NULL); if(index >= graph_vertex_count(g)) { return NULL; } return (Vertex *)darray_index(g->vertices, index); }
int main(int argc, char **argv){ Graph g; int i; int j; g = graph_create(TEST_SIZE); assert(graph_vertex_count(g) == TEST_SIZE); for (i = 0; i < TEST_SIZE; i++){ for (j = 0; j < TEST_SIZE; j++){ assert(graph_has_edge(g, i, j) == 0); } } for (i = 0; i < TEST_SIZE; i++){ assert(graph_out_degree(g, i) == 0); graph_foreach(g, i, match_sink, 0); } assert(graph_edge_count(g) == 0); for (i = 0; i < TEST_SIZE; i++){ for (j = 0; j < TEST_SIZE; j++){ if (i < j){ graph_add_edge(g, i, j); } } } for (i = 0; i < TEST_SIZE; i++){ for (j = 0; j < TEST_SIZE; j++){ assert(graph_has_edge(g, i, j) == (i < j)); } } assert(graph_edge_count(g) == (TEST_SIZE*(TEST_SIZE-1)/2)); graph2dot(g); graph_destroy(g); return 0; }
void dijkstra(graph_t *graph, int source, int *dist, int *parent) { push_data_t data; pq_elem_t e; int n, i; if (!dist) return; data.dist = dist; data.pq = pq_create(sizeof(pq_elem_t), pq_elem_compare); if (!data.pq) return; n = graph_vertex_count(graph); for (i=0; i<n; i++) dist[i] = INT_MAX; if (parent) { for (i=0; i<n; i++) { parent[i] = DIJKSTRA_NULL_PARENT; } } push(graph, source, source, -INT_MAX, &data); while(! pq_is_empty(data.pq)) { pq_delete_min(data.pq, &e); printf("%d -> %d: %d\n", e.source, e.sink, e.distance); if (dist[e.sink] == INT_MAX) { /* new edge */ dist[e.sink] = e.distance; if (parent) parent[e.sink] = e.source; graph_foreach_weighted(graph, e.sink, push, &data); } } pq_destroy(data.pq); }
int main(int argc, char *argv[]) { graph_t *graph; int i, n, *dist, *parent; graph = graph_create(NUM_ELEM); graph_add_weighted_edge(graph, 0, 9, 200); graph_add_edge(graph, 0, 2); graph_add_edge(graph, 0, 4); graph_add_edge(graph, 0, 6); graph_add_edge(graph, 2, 4); graph_add_edge(graph, 2, 7); graph_add_edge(graph, 7, 9); printf("\nAll edges: \n"); graph_print_edges(graph); printf("\nAll edges from 0: \n"); graph_foreach_weighted(graph, 0, &graph_print_edge_weight, NULL); printf("\nDijkstra: \n"); n = graph_vertex_count(graph); dist = malloc(sizeof(int) * n); parent = malloc(sizeof(int) * n); dijkstra(graph, 0, dist, parent); for (i=0; i<n; i++) if (dist[i] == INT_MAX) printf(" no "); else printf("%3d ", dist[i]); printf("\n"); for (i=0; i<n; i++) printf("%3d ", parent[i]); printf("\n"); graph_destroy(graph); return EXIT_SUCCESS; }