18.04.2013 Views

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Topological Sorting<br />

Next: Articulation Vertices Up: Applications of Graph Traversal Previous: Two-Coloring Graphs<br />

Topological Sorting<br />

Figure: Directed acyclic and cyclic graphs<br />

A directed, acyclic graph, or DAG, is a directed graph with no directed cycles. Although undirected<br />

acyclic graphs are limited to trees, DAGs can be considerably more complicated. <strong>The</strong>y just have to avoid<br />

directed cycles, as shown in Figure .<br />

A topological sort of a directed acyclic graph is an ordering on the vertices such that all edges go from<br />

left to right. Only an acyclic graph can have a topological sort, because a directed cycle must eventually<br />

return home to the source of the cycle. However, every DAG has at least one topological sort, and we can<br />

use depth-first search to find such an ordering. Topological sorting proves very useful in scheduling jobs<br />

in their proper sequence, as discussed in catalog Section .<br />

Depth-first search can be used to test whether a graph is a DAG, and if so to find a topological sort for it.<br />

A directed graph is a DAG if and only if no back edges are encountered during a depth-first search.<br />

Labeling each of the vertices in the reverse order that they are marked completely-explored finds a<br />

topological sort of a DAG. Why? Consider what happens to each directed edge as we encounter it<br />

during the exploration of vertex u:<br />

● If v is currently undiscovered, then we then start a DFS of v before we can continue with u. Thus v<br />

is marked completely-explored before u is, and v appears before u in the topological order, as it<br />

must.<br />

● If v is discovered but not completely-explored, then is a back edge, which is forbidden in a<br />

DAG.<br />

● If v is completely-explored, then it will have been so labeled before u. <strong>The</strong>refore, u appears before<br />

v in the topological order, as it must.<br />

file:///E|/BOOK/BOOK2/NODE70.HTM (1 of 2) [19/1/2003 1:29:10]

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

Saved successfully!

Ooh no, something went wrong!