Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created April 23, 2014 21:53
Show Gist options
  • Save gabhi/11233744 to your computer and use it in GitHub Desktop.
Save gabhi/11233744 to your computer and use it in GitHub Desktop.
Graph BFS
/*
Step 1: Push the root node in the Queue.
Step 2: Loop until the queue is empty.
Step 3: Remove the node from the Queue.
Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the unvisited children in the queue.
*/
public void bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove();
Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment