Created
February 27, 2015 22:29
-
-
Save zachschultz/0ab2aa98cb04c1f9f406 to your computer and use it in GitHub Desktop.
Iterative Depth First Search on Nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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