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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Traversing a Graph<br />

Next: Breadth-First Search Up: Graph <strong>Algorithm</strong>s Previous: War Story: Getting the<br />

Traversing a Graph<br />

Perhaps the most fundamental graph problem is to traverse every edge and vertex in a graph in a<br />

systematic way. Indeed, most of the basic algorithms you will need for bookkeeping operations on<br />

graphs will be applications of graph traversal. <strong>The</strong>se include:<br />

● Printing or validating the contents of each edge and/or vertex.<br />

● Copying a graph, or converting between alternate representations.<br />

● Counting the number of edges and/or vertices.<br />

● Identifying the connected components of the graph.<br />

● Finding paths between two vertices, or cycles if they exist.<br />

Since any maze can be represented by a graph, where each junction is a vertex and each hallway an edge,<br />

any traversal algorithm must be powerful enough to get us out of an arbitrary maze. For efficiency, we<br />

must make sure we don't get lost in the maze and visit the same place repeatedly. By being careful, we<br />

can arrange to visit each edge exactly twice. For correctness, we must do the traversal in a systematic<br />

way to ensure that we don't miss anything. To guarantee that we get out of the maze, we must make sure<br />

our search takes us through every edge and vertex in the graph.<br />

<strong>The</strong> key idea behind graph traversal is to mark each vertex when we first visit it and keep track of what<br />

we have not yet completely explored. Although bread crumbs or unraveled threads are used to mark<br />

visited places in fairy-tale mazes, we will rely on Boolean flags or enumerated types. Each vertex will<br />

always be in one of the following three states:<br />

● undiscovered - the vertex in its initial, virgin state.<br />

● discovered - the vertex after we have encountered it, but before we have checked out all its<br />

incident edges.<br />

● completely-explored - the vertex after we have visited all its incident edges.<br />

Obviously, a vertex cannot be completely-explored before we discover it, so over the course of the<br />

traversal the state of each vertex progresses from undiscovered to discovered to completely-explored.<br />

We must also maintain a structure containing all the vertices that we have discovered but not yet<br />

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

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

Saved successfully!

Ooh no, something went wrong!