Objectives of this lecture
Traversal methods
Depth-first traversal:
Breadth-first traversal:
Depth-first Algorithm:
Vist(v)for all vertices w adjacent to v do Traverse(w);
/* DepthFirst: depth-first traversal of a graph.Pre: The graph G has been created.Post: The function Visit has been performed at each vertex of G indepth-first order.Uses: Function Traverse produces the recursive depth-first order. */void DepthFirst(Graph G){ Boolean visited[MAXVERTEX]; Vertex v; for (all v in G) visited[v] = FALSE; for (all v in G) if (!visited[v]) Traverse(v, Visit);} /* Traverse: recursive traversal of a graphPre: v is a vertex of the graph G.Post: The depth-first traversal, using function Visit, has been completed for v and for all vertices adjacent to v.Uses: Traverse recursively. */void Traverse(Vertex v){ Vertex w; visited[v] = TRUE; Visit(v); for (all w adjacent to v) if (!visited[w]) Traverse(w, Visit);}
Breadth-first Algorithm:
/* BreadthFirst: breadth-first traversal of a graph.Pre: The graph G has been created.Post: The function Visit has been performed at each vertex of G, where the vertices are chosen in breadth-first order.Uses: Queue functions. */void BreadthFirst(Graph G){ Queue Q; /* QueueEntry defined to be Vertex. */ Boolean visited[MAXVERTEX]; Vertex v, w; for (all v in G) visited[v] = FALSE; CreateQueue(Q); for (all v in G) if (!visited[v]) { Append(v, Q); do { Serve(v,Q); if (!visited[v]) { visited[v] = TRUE; Visit(v); } for (all w adjacent to v) if (!visited[w]) Append(w, Q); } while (!QueueEmpty(Q)); }}