Traversing Graphs

When we traverse a graph, we visit each vertex in the graph exactly once.

In general, there are two ways to do this:

Depth-First Searches

Depth-first searches, which mimics the exploration of a maze, can be implemented either with stacks or recursion. The process using a stack, is given below:

1. Push a starting vertex, s, onto the stack.
2. Repeat the following until the stack is empty:
      a. Remove the top vertex, v.
      b. Mark this vertex as "visited".
      c. Add all v's unvisited neighbors to the stack.

Breadth-First Searches

Breadth-first searches, which examine vertices in increasing distance from the starting vertex, can be implemented with a queue. The process for doing so is shown below:

1. Enqueue a starting vertex, s, into the queue.
2. Repeat the following until the queue is empty:
     a. Dequeue the least recently added vertex v.
     b. Enqueue each of v's unvisited neighbors, marking each as visited.

Breadth-first searches can be used to find the shortest paths (in terms of number of edges) from the starting vertex $s$. In a connected graph, the time it takes to do this is proportional to $E+V$, the sum of the number of edges and the number of vertices. (Note, every vertex and edge are visited exactly once.)