The general idea behind a depth-first traversal of a graph is this: Start at any vertex, go off in any direction, and keep going until you can proceed no further. Then, back up till you reach a vertex from which you can again go off in some direction. Go off in that direction till you can't go any further ... and so on. Keep repeating this procedure (being careful to note the places you've already visited so you don't visit them again) until you back up to the starting vertex, at which point you're done. Note that a pre-order tree traversal is one form of a depth-first graph traversal.
Here is the pseudocode:
DoItDepthFirst(graph, startVertex, other_parameters_if_required) ---------------------------------------------------------------- Visit startVertex Mark startVertex as visited for every vertex v adjacent to startVertex (in ascending key order) DoItDepthFirst(graph, v, other_parameters_if_required)
We follow the convention of going in the direction of the smallest key whenever we have a choice of direction in which to go. This will give us a unique depth-first traversal.
The general idea behind a breadth-first traversal of a graph is this: Start at any vertex. Visit all the neighbors of that vertex. Then visit all the neighbors of those neighbors. And so on, until there are no neighbors of neighbors of neighbors ... left to visit. Note that a level-order tree traversal is one form of a breadth-first graph traversal.
Here is the pseudocode
:DoItBreadthFirst(graph, startVertex, other_parameters_if_required) ------------------------------------------------------------------ Visit startVertex Mark startVertex as visited Put startVertex into a queue while the queue is not empty Remove next vertex v from queue for each vertex w adjacent to v (in ascending key order in w) if w is not marked as visited Visit w Mark m as visited Put w into the queue
Once again, we follow the convention of going in the direction of the smallest key whenever we have a choice of direction in which to go and, whenever we have a choice of starting points, we also choose the starting point with the smallest key. This will give us a unique breadth-first traversal.