Skip to content

Instantly share code, notes, and snippets.

@gabhi
Last active August 29, 2015 14:00
Show Gist options
  • Save gabhi/11233655 to your computer and use it in GitHub Desktop.
Save gabhi/11233655 to your computer and use it in GitHub Desktop.
Graph DFS
/*
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