Breadth-first search (version 2)
BFS(k,n) { /* k = starting vertex; n = number of vertices in the graph */
Queue Q; /* declare a queue Q */
bit seen[n]; /* declare a bit vector seen */
INIT(Q);
seen[0..n-1] = all 0’s;
enqueue(Q, k);
while (!empty(Q)) {
i = dequeue(Q); output(i);
for each neighbor j of i
if (!seen[j]) {
enqueue(Q, j); seen[j]=1;
}}} 77
Replace Queue with Stack
Search(k,n) { /* k = start; n = number of vertices in the graph */
Stack S; /* declare a stack S */
bit visited[n]; /* declare a bit vector visited */
INIT(S); visited[0..n-1] = all 0’s;
[Link](k);
while (!empty(S)) {
i = [Link]();
if (!visited[i]) {
visited[i] = 1; Output(i); Function(i);
for each neighbor j of i
if (!visited[j]) [Link](j);}}}
78
Example
79
Depth first search: Recursive
Data structure: an array Visited [1..n]
Initialization: Visited [v] := false for all vertices v.
DFS(k); // k is the start
DFS(i)
1. Visited[i] := true; Output(i); Function(i);
2. For each vertex j in the adjacent list of i,
if (!Visited[j])
then DFS(j) ;
Recursive call
80