11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

386 Chap. 11 Graphs/** Breadth first (queue-based) search */st<strong>at</strong>ic void BFS(Graph G, int start) {Queue Q = new AQueue(G.n());Q.enqueue(start);G.setMark(start, VISITED);while (Q.length() > 0) { // Process each vertex on Qint v = Q.dequeue();}}PreVisit(G, v);// Take appropri<strong>at</strong>e actionfor (int w = G.first(v); w < G.n(); w = G.next(v, w))if (G.getMark(w) == UNVISITED) { // Put neighbors on QG.setMark(w, VISITED);Q.enqueue(w);}PostVisit(G, v);// Take appropri<strong>at</strong>e actionFigure 11.10 Implement<strong>at</strong>ion for the breadth-first graph traversal algorithmABABCCDDFFEE(a)(b)Figure 11.11 (a) A graph. (b) The breadth-first search tree for the graph whenstarting <strong>at</strong> Vertex A.illustr<strong>at</strong>es the problem. An acceptable topological sort for this example is J1, J2,J3, J4, J5, J6, J7.A topological sort may be found by performing a DFS on the graph. When avertex is visited, no action is taken (i.e., function PreVisit does nothing). Whenthe recursion pops back to th<strong>at</strong> vertex, function PostVisit prints the vertex. Thisyields a topological sort in reverse order. It does not m<strong>at</strong>ter where the sort starts, aslong as all vertices are visited in the end. Figure 11.13 shows an implement<strong>at</strong>ionfor the DFS-based algorithm.Using this algorithm starting <strong>at</strong> J1 <strong>and</strong> visiting adjacent neighbors in alphabeticorder, vertices of the graph in Figure 11.14 are printed out in the order J7, J5, J4,J6, J2, J3, J1. Reversing this yields the topological sort J1, J3, J2, J6, J4, J5, J7.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!