Traversals through graphs

Just like with trees one needs algorithms that will enable you to visit each node in a graph and do "stuff" - in other words, you need an iterator. There are two basic ways to construct iterators in a graph.

A breadth-first traversal of a graph is the following algorithm. (From here on we will we assume that the vertices are labeled with the numbers from 0 to n-1 where n=|V| is the number of vertices.)

Copy the set of vertices from V into a set T
Create an array of booleans of size n called Marked and set every element to false
Create Queue Q
nComponents=0
While T is not empty
    nComponents++;
    Take an element w from T and enqueue it in Q and set Marked[w]=true
     While Q is not empty
          Dequeue the first node v from Q
          For every node u such that <v,u> is an edge and for which Marked[u]=false
             Enqueue u in Q and set Marked[u] to true
          end For
          remove v from T
    end While
end While
    
Notice that if our graph is represented by an adjacency list, then this algorithm takes time roughlly Cm+Dn where m is the number of edges and n is the number of vertices and is, therefore, of time order of m+n. Notice also that each time through the outer loop visits one connected component so if the outer loop increments a counter nComponents each time through, then if nComponents ends up being 1 the graph was connected. Otherwise, nComponents is the number of components.

A depth-first traversal of a graph is the following algorithm:
OverallDFS()
    Create array Marked of length n=|V| and set all elements of Marked false
    Copy each element of V to set T
    nComponents=0;
    While there is at least one element u left in T
             nComponents++;
             DFS(u)
    end While
end OverallDFS
      
DFS(u):
    Set Marked[u]=true;
    Remove u from T
    for each eddge <u,v>
       if !Marked[v]
          DFS(v)
       end if
    end for
end DFS