790 likes | 1.04k Views
Graph Traversal. Chapter 9. Problem. Given a directed or undirected graph G=(V,E), find a way to traverse all of its vertices. Solution. Depth First Search (DFS) Breadth First Search (BFS). DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS. DFS.
E N D
Graph Traversal Chapter 9
Problem • Given a directed or undirected graph G=(V,E), find a way to traverse all of its vertices.
Solution • Depth First Search (DFS) • Breadth First Search (BFS)
DFS And so on ...
DFS • We need also to record • the birth time of any node: the time of the first visit to the node. • the death time: the time after all of its children are visited and ..also dead
Algorithm: DFS Input:graph G=(V,E) directed or undirected Output:preordering of the vertices in DFS spanning tree (or forest) • predfn 0; postdfn 0; % global variables • For each vertex vV • mark v unvisited • End for • For each vV % for connected components • if v is unvisited then dfs(v) • End for
Procedure dfs(v) • Mark v visited • predfn predfn + 1 % birth time • For each edge (v,w) E • if w is marked unvisited then dfs(w) • End for • postdfn postdfn + 1 % death time
Definitions • In a directed graph, (u,v) is • a tree edge, if it is in the DFS tree, i.e., v is marked unvisited • back edge, if v is marked visited & ancestor of u • Forward edge, if v marked visited & descendant of u • Cross edge, if it is otherwise.
Tree edge back edge Cross edge Forward edge
Definitions • In an undirected graph, (u,v) is • a tree edge if it is in the DFS tree • back edges, otherwise.
Example 1 a d e c f b
Example 1 a d e c f 2 b
Example 1 a d e c f 2 b 3
Example 1 4 a d e c f 2 b 3
Example 1 4 a d e c f 2 b 5 3
Example 1 4 a d e Back edge c f 2 b 5 3
Example 1 4 a d e Back edge c f 2 b 5, 1 3
Example 6 1 4 a d e Back edge c f 2 b 5, 1 3
Example 6 1 4 a d e Cross edge Back edge c f 2 b 5, 1 3
Example 6 1 4 a d e Cross edge Back edge Back edge c f 2 b 5, 1 3
Example 6, 2 1 4 a d e Cross edge Back edge Back edge c f 2 b 5, 1 3
Example 6, 2 1 4, 3 a d e Cross edge Back edge Back edge c f 2 b 5, 1 3
Example 6, 2 1 4, 3 a d e Cross edge Back edge Back edge c f 2 b 5, 1 3, 4
Example 6, 2 1 4, 3 a d e Cross edge Back edge Back edge c f 2, 3 b 5, 1 3, 4
Example 6, 2 Forward edge 1 4, 3 a d e Cross edge Back edge Back edge c f 2, 3 b 5, 1 3, 4
Example 6, 2 Forward edge 1, 6 4, 3 a d e Cross edge Back edge Back edge c f 2, 5 b 5, 1 3, 4
Analysis of DFS • Time = (m + n) Applications: • Testing acyclicity (is G a tree?) • Strongly connected components