-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbfs.c
More file actions
68 lines (55 loc) · 1.5 KB
/
bfs.c
File metadata and controls
68 lines (55 loc) · 1.5 KB
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
#include <stdio.h>
#include "graphArr.h"
// BFS queue (circular buffer)
int queue[NUM_NODES];
int head = 0;
int tail = 0;
// Visited array and distances
char visited[NUM_NODES];
int distance[NUM_NODES];
// BFS traversal from a starting node
// Returns the sum of all distances (to prevent optimization)
int bfs(int start) {
// Initialize
for (int i = 0; i < NUM_NODES; i++) {
visited[i] = 0;
distance[i] = -1;
}
head = 0;
tail = 0;
// Enqueue start node
queue[tail++] = start;
visited[start] = 1;
distance[start] = 0;
int sum = 0;
while (head != tail) {
// Dequeue
int node = queue[head++];
if (head >= NUM_NODES) head = 0; // wrap around
int dist = distance[node];
sum += dist;
// Visit all neighbors
int edge_start = row_start[node];
int edge_end = row_start[node + 1];
for (int e = edge_start; e < edge_end; e++) {
int neighbor = neighbors[e];
if (!visited[neighbor]) {
visited[neighbor] = 1;
distance[neighbor] = dist + 1;
queue[tail++] = neighbor;
if (tail >= NUM_NODES) tail = 0; // wrap around
}
}
}
return sum;
}
int main(int argc, char *argv[]) {
// Run BFS from two different starting points
int total = 0;
total += bfs(0);
total += bfs(NUM_NODES / 2);
if (argc >= 2) {
printf("bfs_sum:%d, %s\n", total, argv[0]);
}
return 0;
}