To traverse a graph is to process every node in the graph exactly once. Because there are many paths leading from one node to another, the hardest part about traversing a graph is making sure that you do not process some node twice. There are two general solutions to this difficulty:
- when you first encounter a node, mark it as REACHED. When you visit a node, check if it’s marked REACHED; if it is, just ignore it. This is the method our algorithms will use.
- when you process a node, delete it from the graph. Deleting the node causes the deletion of all the arcs that lead to the node, so it will be impossible to reach it more than once.
At the heart of our traversal algorithm – and in fact all of our algorithms – is a list of nodes that we have reached but not yet processed. we will call this the READY list.
General Traversal Strategy
- Mark all nodes in the graph as NOT REACHED.
- pick a starting node. Mark it as REACHED and place it on the READY list.
- pick a node on the READY list. Process it. Remove it from READY. Find all its neighbours: those that are NOT REACHED should marked as REACHED and added to READY.
- repeat 3 until READY is empty.