CSC 213 – Large Scale Programming Lecture 31: Graph Traversals
Subgraphs Subgraph of a graph G must contain only edges & vertices from G Spanning subgraph contains all vertices from the graph Subgraph Spanning subgraph
Connected Graph Connected if path exists between every pair of vertices Requires a path, not an edge between vertices Connected component is subgraph containing all connected vertices Maximal connected Connected graph Graph with two connected components
Tree Connected, undirected, acyclic graph Just like Tree data structures Forest is graph containing multiple trees Tree Forest
Spanning Tree Subgraph that is spanning subgraph & tree Spanning subgraph must contain all vertices Tree must be connected without any cycles Spanning Tree
Depth- & Breadth-First Search Common graph traversal algorithms DFS & BFS traversals Visits all vertices and edges in G Computes if G is connected Finds connected components if G not connected Used frequently to solve graph problems
DFS and Maze Traversal Classic maze exploring strategy Each intersection, corner, & dead end is a vertex Corridors become edges DFS marks corridors traveled Marks lead back to start
DFS Example DB A C ED B A C E D B A C E discovery edge back edge A visited vertex A unexplored vertex unexplored edge
DFS Example (cont.) DB A C E DB A C E DB A C E D B A C E
Properties of DFS Visits all vertices and edges in a connected component Edges followed form a spanning tree for the connected component DB A C E
BFS Example C B A E D discovery edge cross edge A visited vertex A unexplored vertex unexplored edge L0L0 L1L1 F CB A E D L0L0 L1L1 F CB A E D L0L0 L1L1 F
BFS Example (cont.) CB A E D L0L0 L1L1 F CB A E D L0L0 L1L1 F L2L2 CB A E D L0L0 L1L1 F L2L2 CB A E D L0L0 L1L1 F L2L2
CB A E D L0L0 L1L1 F L2L2 CB A E D L0L0 L1L1 F L2L2 CB A E D L0L0 L1L1 F L2L2
Properties of BFS Also visits all the vertices and edges in a connected component Discovery edges create spanning tree of the component For each vertex v in L i Path from s to v in spanning tree has exactly i edges No paths from s to v in G has fewer than i edges CB A E D L0L0 L1L1 F L2L2
DFS vs. BFS Back edge (v,w) w is ancestor of v in tree of discovery edges Cross edge (v,w) v in same or previous level as w in tree of discovery edges CB A E D L0L0 L1L1 F L2L2 CB A E D F DFSBFS
For Next Lecture Review all our work with Graphs so far Come ready with questions you have Have fun & interesting problems to work on