Reputation: 1027
So I'm attempted to implement the following Graph DFS method:
/** Performs a depth-first traversal of G over all vertices
* reachable from V. That is, the fringe is a sequence and
* vertices are added to it or removed from it at one end in
* an undefined order. After the traversal of all successors of
* a node is complete, the node itself is revisited by calling
* the postVisit method on it. */
public void depthFirstTraverse(Graph<VLabel, ELabel> G,
Graph<VLabel, ELabel>.Vertex v) {
Stack<Vertex> fringe = new Stack<Vertex>();
HashSet<Vertex> marked = new HashSet<Vertex>();
fringe.push(v);
while (!fringe.isEmpty()) {
Vertex vert = fringe.pop();
if (!marked.contains(vert)) {
marked.add(vert);
visit(vert);
for (Edge edge : G.edges(vert)) {
preVisit(edge, vert);
fringe.add(edge.getV1());
}
}
}
}
I have the general algorithm correct according to my tests, but I'm still missing the requirement in the last sentence: "After the traversal of all successors of a node is complete, the node itself is revisited by calling the postVisit method on it."
I'm rather stumped on how to add this postVisit method in iteratively (can't change the function signature so recursion is out of the question). Any ideas?
Upvotes: 3
Views: 1196
Reputation: 1090
You need a stack, the possibility to mark a vertex as visited, and to mark a vertex as processed. As long as the stack is not empty, you do the following where v is the top vertex on the stack.
Upvotes: 4