Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterative Depth First Search on Nodes
public void DFS_Iterative(Node n) {
Stack<Node> stack = new Stack<Node>();
stack.push(n);
while (!stack.isEmpty()) {
Node node = stack.pop();
if (!node.visited) {
node.visited = true;
System.out.println(node);
Stack<Node> tempStack = new Stack<Node>();
for (Node x: node.adjList) {
if (!x.visited)
tempStack.push(x);
}
while (!tempStack.isEmpty())
stack.push(tempStack.pop());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.