-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.c
70 lines (61 loc) · 1.97 KB
/
graph.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdlib.h>
#include <float.h>
#include "graph.h"
struct Graph {
Vector *nodes;
};
Graph *graph_construct(int num_nodes) {
Graph *g = calloc(1, sizeof(Graph));
if (g == NULL)
exit(printf("Error: graph_construct failed to allocate memory.\n"));
g->nodes = vector_construct();
for (int i = 0; i < num_nodes; i++) {
Node *n = node_construct();
vector_push_back(g->nodes, n);
}
return g;
}
void graph_destruct(Graph *graph) {
vector_destroy(graph->nodes, (data_type)node_destruct);
free(graph);
}
void graph_add_node(Graph *graph, int src, int neighbor, float weight){
Node *n = (Node *) vector_get(graph->nodes, src);
node_add_connection(n, neighbor, weight);
}
void graph_read(Graph* graph, FILE *file) {
int neighbor;
float weight;
char c;
for (int i = 0; i < vector_size(graph->nodes); ++i) {
while (1) {
c = '-';
fscanf(file, "%d %f%c", &neighbor, &weight, &c);
graph_add_node(graph, i, neighbor, weight);
if (c != ' ') {
break;
}
}
}
//debug
// printf("node neighbor weight\n");
// for (int i = 0; i < vector_size(graph->nodes); ++i) {
// Node *n = (Node *) vector_get(graph->nodes, i);
// for (int j = 0; j < node_get_num_connections(n); ++j) {
// Connection *c = node_get_connection(n, j);
// printf("%d\t%d\t%f\n", i, connection_get_neighbor(c), connection_get_weight(c));
// }
// }
// exit(0);
}
Connection *graph_get_connection(Graph *graph, int idx_neighbor, int idx_connection) {
Node *n = (Node *) vector_get(graph->nodes, idx_neighbor);
return node_get_connection(n, idx_connection);
}
int graph_get_num_connections_from_node(Graph *graph, int idx) {
Node *n = (Node *) vector_get(graph->nodes, idx);
return node_get_num_connections(n);
}
int graph_get_num_nodes(Graph *graph) {
return vector_size(graph->nodes);
}