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.
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.
Exercise #3, p. 452/456
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.
Exercise #13, p. 453/457
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:
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.