main() { void BFS(NODE v) {
NODE v; NODE w;
queueinit(): enqueue(v);
for (all nodes v) visited[v] = FALSE; while (!queueempty()) {
for (all nodes v) v = dequeue();
if (!visited[v]) visited[v] = TRUE;
BFS(v); for (all neighbors w of v)
} if (!visited[w]) {
visited[w] = TRUE;
enqueue(w);
}
} }
BFS: bfs [175]
% gcc -o bfs bfs.c > tcc bfs.c
Data File with Test Case: graph.dat
% bfs graph.dat n: 10 steps: 100
ANALYSIS: for every node, for every neighbor: O( )
DFS Spanning Forest:
% bfs graph.dat graph 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
BFS: bfs graph.dat step [176]
v w step v w step v w step v w step v w step 1 1 1 + 4 3 23 x 6 2 42 x 7 3 63 x 10 3 83 x 1 1 1 - 4 4 24 + 6 3 43 + 7 4 64 x 10 4 84 x 1 2 2 + 4 4 24 - 6 3 43 - 7 5 65 x 10 5 85 x 1 3 3 x 4 5 25 + 6 4 44 x 7 6 66 + 10 6 86 x 1 4 4 + 4 6 26 x 6 5 45 x 7 6 66 - 10 7 87 x 1 5 5 x 4 7 27 x 6 6 46 + 7 7 67 + 10 8 88 x 1 6 6 x 4 8 28 x 6 6 46 - 7 7 67 - 10 9 89 + 1 7 7 x 4 9 29 x 6 7 47 x 7 8 68 + 10 10 90 + 1 8 8 x 4 10 30 x 6 8 48 x 7 9 69 x 10 10 90 - 1 9 9 x 3 1 31 + 6 9 49 x 7 10 70 x 9 1 91 x 1 10 10 x 3 1 31 - 6 10 50 x 8 1 71 x 9 2 92 x 2 1 11 x 3 2 32 x 5 1 51 x 8 2 72 x 9 3 93 x 2 2 12 + 3 3 33 + 5 2 52 x 8 3 73 x 9 4 94 x 2 2 12 - 3 3 33 - 5 3 53 x 8 4 74 x 9 5 95 x 2 3 13 + 3 4 34 + 5 4 54 x 8 5 75 x 9 6 96 x 2 4 14 x 3 4 34 - 5 5 55 + 8 6 76 + 9 7 97 x 2 5 15 x 3 5 35 + 5 5 55 - 8 6 76 - 9 8 98 + 2 6 16 + 3 5 35 - 5 6 56 x 8 7 77 x 9 8 98 - 2 7 17 x 3 6 36 x 5 7 57 x 8 8 78 + 9 9 99 + 2 8 18 x 3 7 37 x 5 8 58 x 8 8 78 - 9 9 99 - 2 9 19 x 3 8 38 x 5 9 59 x 8 9 79 x 9 10 100 x 2 10 20 x 3 9 39 x 5 10 60 x 8 10 80 + 4 1 21 x 3 10 40 x 7 1 61 x 10 1 81 x 4 2 22 x 6 1 41 x 7 2 62 x 10 2 82 x
BFS: bfs.c [177]
typedef int NODE;
int A[MAX][MAX], B[MAX][MAX];
int queue[MAX], front, rear;
int val[MAX];
int n, label=0;
void enqueue(NODE v) {
rear++;
if (rear >= MAX) rear = 0;
queue[rear] = v;
}
int dequeue() {
NODE v;
v = queue[front];
front++;
if (front >= MAX) front = 0;
return(v);
}
void queueinit() { front = 1; rear = 0; }
int queueempty() { return(front == rear+1); }
void BFS(NODE v) {
NODE w;
enqueue(v);
while (!queueempty()) {
v = dequeue();
val[v] = ++label;
for (w = 1; w<= n; w++)
if (A[v][w])
if (val[w] == 0) {
enqueue(w);
B[v][w] = 1;
val[w] = -1;
}
}
}
void main(int argc, char *argv[]) {
NODE v;
getdata(argc,argv);
queueinit();
label=0;
for (v=1; v<=n; v++) val[v] = 0;
for (v=1; v<=n; v++)
if (val[v] == 0) BFS(v);
}