Skip to content

Instantly share code, notes, and snippets.

@zachschultz
Created February 27, 2015 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachschultz/0ab2aa98cb04c1f9f406 to your computer and use it in GitHub Desktop.
Save zachschultz/0ab2aa98cb04c1f9f406 to your computer and use it in GitHub Desktop.
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