80 likes | 101 Views
Learn about Breadth-First and Depth-First Search algorithms to traverse a graph and find all reachable vertices.
E N D
Recall: Breadth First Traversal • Problem: • Given a graph, G = (V, E), find all the vertices reachable from some source, s. • Repeat for all unvisited vertices • Strategy: • Visit all vertices adjacent to s first. • Traversal expands outward level by level. (Visit all vertices a distance of 2 away from s second, then those at distance 3, etc.) • Keep track of nodes that have been visited already (Otherwise may visit a vertex twice or end up in an endless cycle).
Pseudocode for Breadth First Traversal template <intmax_size> void Digraph <max_size>:: breadth_first(void (*visit)(vertex &)) const { Queue q; boolvisited[max_size]; Vertex v, w, x; for (all v in G) visited[v] = false; for (all v in G) if (!visited[v]) { q.append(v); while(!q.empty( )) { q.retrieve(w); if(!visited[w]) { visited[w] = true; (*visit)(w); for (all x adjacent to w) q.append(x); } q.serve( ); } } }
Example a b c d e f g h We will work through this in class.
Depth First Search • Idea: Explore the graph from a vertex by searching as far (deep) as you can along a given path. • When you have moved as far as you can go, back up until you find a vertex with unexplored neighbors. Follow these paths to the end. • Continue until all vertices reachable from the original have been explored. • If any undiscovered vertices remain (e.g. if the graph is unconnected), one of them is selected as a new source and the search is repeated. • Repeat until all vertices are discovered.
Pseudocode for Depth First Traversal template <int max_size> void Digraph <max_size>:: depth_first(void (*visit)(vertex &)) const { bool visited[max_size]; Vertex v; for (all v in G) visited[v] = false; for (all v in G) { if (!visited[v]) traverse(v, visited, visit); } }
Pseudocode for Depth First Traversal--continued template <int max_size> void Digraph <max_size>:: traverse(Vertex &v, bool visited[ ], void (*visit)(vertex &)) const { Vertex w; visited[v] = true; (*visit)(v); for (all w adjacent to v) { if(!visited[w]) traverse(w, visited, visit); } }
Example a b c d e f g h We will work through this in class.