Code Fragment: DFS1



template <typename Graph>
class DFS {
protected: 						// local types
  typedef typename Graph::Vertex	    Vertex;
  typedef typename Graph::Edge		    Edge;
  typedef typename Graph::VertexIterator    VertexIterator;
  typedef typename Graph::EdgeIterator	    EdgeIterator;
protected: 						// member data
  const Graph& G;					// the graph
  Object *visited, *unvisited;				// decorator values
public:
  DFS(const Graph& g) : G(g)				// constructor
    { visited = new Object; unvisited  = new Object; }
  void initialize() {					// initialize a new DFS
    VertexIterator V = G.vertices();			// unmark everything
    while (V.hasNext()) markUnvisited(V.nextVertex());
    EdgeIterator E = G.edges();
    while (E.hasNext()) markUnvisited(E.nextEdge());
  }
  virtual ~DFS()
    { delete visited; delete unvisited; }		// destructor
protected: 						// marking utilities
  void dfsTraversal(const Vertex& v) {			// generic DFS search
    startVisit(v);					// visit v
    markVisited(v);					// mark v visited
    EdgeIterator inEdges = G.incidentEdges(v);
    while (inEdges.hasNext()) {				// try all its edges
      Edge e = inEdges.nextEdge();
      if (!isVisited(e)) {				// new edge?
        markVisited(e);					// mark it visited
        Vertex w = G.opposite(v, e);			// get next vertex
        if (!isVisited(w)) {				// unexplored?
          traverseDiscovery(e, v);			// let's discover it
          if (!isDone())
            dfsTraversal(w);				// continue traversal
        }
        else 						// explored
          traverseBack(e, v);				// process back edge
      }
    }
    finishVisit(v);					// all done
  }
  // ... (insert overriden functions and marking utilities here)
};