Breadth first search in java


If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

We have already seen about breadth first search in level order traversal of binary tree.

Graph traversal Algorithms:

Breadth first search in javaDepth first search in javaBreadth first search is graph traversal algorithm. In this algorithm, lets say we start with node i, then we will visit neighbours of i, then neighbours of neighbours of i and so on.

It is very much similar to which is used in binary tree. We use queue to traverse graph. We put first node in queue . It repeatedly extracts node and put its neighbours in the queue. Only difference with respect to binary tree is that we need to track if node have been visited before or not. It can be easily done with help of boolean variable visited in the node. If node have been already visited then we won’t visit it again.


Steps for Breadth first search:

  1. Create empty queue and push root node to it.
  2. Do the following when queue is not empty
    • Pop a node from queue and print it.
    • Find neighbours of node with the help of adjacency matrix and check if node is already visited or not.
    • Push neighbours of node into queue if not null

Lets understand with the help of example:
Lets say graph is:

Breadth first search traversal

When you run above program, you will get below output:

Please go through Algorithm Interview Programs in java  for more such programs.


Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog