Last active
August 29, 2015 14:00
-
-
Save gabhi/11233655 to your computer and use it in GitHub Desktop.
Graph DFS
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
/* | |
Step 1: Push the root node in the Stack. | |
Step 2: Loop until stack is empty. | |
Step 3: Peek the node of the stack. | |
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traversed and push it on stack. | |
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack. | |
*/ | |
public void dfs() | |
{ | |
//DFS uses Stack data structure | |
Stack s=new Stack(); | |
s.push(this.rootNode); | |
rootNode.visited=true; | |
printNode(rootNode); | |
while(!s.isEmpty()) | |
{ | |
Node n=(Node)s.peek(); | |
Node child=getUnvisitedChildNode(n); | |
if(child!=null) | |
{ | |
child.visited=true; | |
printNode(child); | |
s.push(child); | |
} | |
else | |
{ | |
s.pop(); | |
} | |
} | |
//Clear visited property of nodes | |
clearNodes(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment