Depth First Search Neil Tang 412010 CS 223

  • Slides: 9
Download presentation
Depth First Search Neil Tang 4/1/2010 CS 223 Advanced Data Structures and Algorithms 1

Depth First Search Neil Tang 4/1/2010 CS 223 Advanced Data Structures and Algorithms 1

Class Overview Ø Breadth First Search (BFS) Ø Depth First Search (DFS) Ø DFS

Class Overview Ø Breadth First Search (BFS) Ø Depth First Search (DFS) Ø DFS on an undirected graph Ø DFS on a digraph Ø Strong connected components CS 223 Advanced Data Structures and Algorithms 2

BFS Ø Visit the nodes that are one-hop away from the starting node one

BFS Ø Visit the nodes that are one-hop away from the starting node one by one, then the nodes that are two-hop away, then …, i. e. , layer by layer. Ø A queue should be used to implement the BFS. Ø Make sure each node is visited exactly once. CS 223 Advanced Data Structures and Algorithms 3

DFS Ø A generalized pre-order traversal Time Complexity: O(|V|+|E|) CS 223 Advanced Data Structures

DFS Ø A generalized pre-order traversal Time Complexity: O(|V|+|E|) CS 223 Advanced Data Structures and Algorithms 4

DFS on An Undirected Graph DFS(A): A, B, C, D, E CS 223 Advanced

DFS on An Undirected Graph DFS(A): A, B, C, D, E CS 223 Advanced Data Structures and Algorithms 5

DFS on An Undirected Graph Ø DFS can be used to find if an

DFS on An Undirected Graph Ø DFS can be used to find if an undirected graph is connected or not. Ø DFS can also be used to find all the connected components. CS 223 Advanced Data Structures and Algorithms 6

DFS on A Digraph DFS(B): B, C, A, D, E, F; DFS(H): H, J,

DFS on A Digraph DFS(B): B, C, A, D, E, F; DFS(H): H, J, I; DFS(G): G. CS 223 Advanced Data Structures and Algorithms 7

Strongly Connected Components Ø Perform DFS until all nodes are visited. Ø Construct an

Strongly Connected Components Ø Perform DFS until all nodes are visited. Ø Construct an auxiliary graph Gr. Ø Perform DFS on Gr in the reverse order of the index numbers. CS 223 Advanced Data Structures and Algorithms 8

Strongly Connected Components Gr DFS(G): G; DFS(H): H, I, J; DFS(B): B, A, C,

Strongly Connected Components Gr DFS(G): G; DFS(H): H, I, J; DFS(B): B, A, C, F; The forest after the first DFS(D): D; DFS(E): E. Strongly Connected Components: (G), (H, I, J), (B, A, C, F), (D), (E) CS 223 Advanced Data Structures and Algorithms 9