Section 6.4: Traversal Algorithms

Abstract:

We've already examined some tree traversal algorithms (pre-order, in-order, post-order), and considered their relative advantages. We now want to open the notion of traversal to all graphs (we certainly might want to write out the nodes of an arbitrary graph!). We examine and compare two recursive methods: depth-first and breadth-first.

Note: we're only covering 6.4 through Practice 16 (p. 449/453).

Important Convention: for the problems, we should stick with the convention that, given a choice, we should choose nodes in alphabetic order.

Depth-First versus Breadth-First Traversal

Depth-First

The idea behind the depth-first strategy is to burrow down into the graph, rather than spread out as one does in a breadth-first traversal. The depth-first algorithm is recursive. Have a look at the algorithm on p. 443/448.

  1. Pick (mark and write) the start node;
  2. Find its neighbor nodes (ordering them lexigraphically, for sanity's sake!);
  3. For each unmarked neighbor x, DepthFirst(G,x)

Exercise #3, p. 452/456

Breadth-First

Examine the breadth-first algorithm on p. 446/450. It uses a queue to traverse the nodes, popping elements off the queue as all of their adjacent nodes are also marked.

  1. Pick (mark and write) the start node;
  2. Find its neighbor nodes (ordering them lexigraphically, for sanity's sake!);
  3. Mark, write, and enqueue those which are as yet unmarked;
  4. Dequeue the front element of the queue;
  5. Continue until the queue is empty.

Exercise #13, p. 453/457

Depth-First Application

These types of traversal algorithms are useful for operating on graphs. For example, I wrote this lisp code to find the shortest distance between two nodes x and y, using a depth-first algorithm (recursively). The idea is this:

Note that I used the adjacency matrix representation, which is good for ``full'' graphs, but wasteful for sparse ones.

To test my algorithm, I ran it on the graph of Exercise #13/15, p. 439/444 for every pair of nodes (to compare the result with Floyd's algorithm). You can try out this procedure using this this web script.



LONG ANDREW E
Fri Nov 8 01:03:57 EST 2002