Graph Traversal: Text Depth-First Search Breadth-First Search
Graph Traversal: Text Depth-First Search Breadth-First Search
Text
Weiss, 9.6 Think Stack Think Queue
Overview
Goal
To systematically visit the nodes of a graph
Depth-First Search
// recursive, preorder, depth-first search void dfs (Node v) { if (v == null) return; if (v not yet visited) visit&mark(v); // visit node before adjacent nodes
for (each w adjacent to v) if (w has not yet been visited) dfs(w); } // dfs
Depth-First Search
// recursive, postorder, depth-first search void dfs (Node v) { if (v == null) return; tag(v); // mark v as having been considered for (each w adjacent to v) if (w has not yet been tagged) dfs(w); visit(v); // postorder traversal: visit node after // adjacent nodes
} // dfs
Depth-First Search
// non-recursive, preorder, depth-first search void dfs (Node v) { if (v == null) return; push(v); while (stack is not empty) { pop(v); if (v has not yet been visited) mark&visit(v); for (each w adjacent to v) if (w has not yet been visited) push(w); } // while } // dfs
Depth-First Search
// non-recursive, postorder, depth-first search void dfs (Node v) {
} // dfs
Example
5 0 1 7 3 4 2
6
5 1 0 3 2 7 6 4
6
5 1
6
5 1 0 7 6 2 4 3
// non-recursive, preorder, depth-first search void dfs (Node v) { if (v == null) return; push(v); while (stack is not empty) { pop(v); if (v has not yet been visited) mark&visit(v);
for (each w adjacent to v) if (w has not yet been visited && not yet stacked) push(w); } // while } // dfs
6
5 1 0 37 6 4 2
6
2 3 6 7 0 4 1 5
Breadth-first Search
Ripples in a pond Visit designated node Then visited unvisited nodes a distance i away, where i = 1, 2, 3, etc. For nodes the same distance away, visit nodes in systematic manner (eg. increasing index order)
Breadth-First Search
// non-recursive, preorder, breadth-first search void bfs (Node v) { if (v == null) return; enqueue(v); while (queue is not empty) { dequeue(v); if (v has not yet been visited) mark&visit(v); for (each w adjacent to v) if (w has not yet been visited && has not been queued) enqueue(w); } // while } // bfs
6
5 1 2 0 4 3 7 6
6
5 1 2 0 4
6
5 1 2 0 4
6
5 1 2 0 4 3 7
6
5 1 2 0 4 3 7
BFS: Visit 6
5 0 1 7 3 4 2
6
5 1 2 0 4 3 7 6