Java Program to Traverse a Graph using BFS

This is the Java Program to do a Breadth First Search/Traversal on a graph non-recursively.

Problem Description

Given a graph in the form of an adjacency matrix and a source vertex, write a program to perform a breadth-first search of the graph. In breadth-first search traversal, nodes are traversed level by level.

Problem Solution

The idea is to store the source vertex in the queue. Now, iterate through the queue until it is empty. For every vertex retrieved from the queue, check which of its neighbours are still not processed. Add those neighbours to the queue.

Program/Source Code

Here is the source code of the Java Program to do a Breadth First Search/Traversal on a graph non-recursively. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to do a Breadth First Search/Traversal on a graph non-recursively
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.LinkedList;
  8. import java.util.Queue;
  9.  
  10. public class BreadthFirstSearch {
  11.     // Function to perform breadth first search
  12.     static void breadthFirstSearch(int[][] matrix, int source){
  13.         boolean[] visited = new boolean[matrix.length];
  14.         visited[source-1] = true;
  15.         Queue<Integer> queue = new LinkedList<>();
  16.         queue.add(source);
  17.         System.out.println("The breadth first order is");
  18.         while(!queue.isEmpty()){
  19.             System.out.println(queue.peek());
  20.             int x = queue.poll();
  21.             int i;
  22.             for(i=0; i<matrix.length;i++){
  23.                 if(matrix[x-1][i] == 1 && visited[i] == false){
  24.                     queue.add(i+1);
  25.                     visited[i] = true;
  26.                 }
  27.             }
  28.         }
  29.     }
  30.     // Function to read user input
  31.     public static void main(String[] args) {
  32.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  33.         int vertices;
  34.         System.out.println("Enter the number of vertices in the graph");
  35.         try{
  36.             vertices = Integer.parseInt(br.readLine());
  37.         }catch(IOException e){
  38.             System.out.println("An error occurred");
  39.             return;
  40.         }
  41.         int[][] matrix = new int[vertices][vertices];
  42.         System.out.println("Enter the adjacency matrix");
  43.         int i,j;
  44.         for(i=0; i<vertices; i++){
  45.             for(j=0; j<vertices; j++){
  46.                 try{
  47.                     matrix[i][j] = Integer.parseInt(br.readLine());
  48.                 }catch (IOException e){
  49.                     System.out.println("An error occurred");
  50.                 }
  51.             }
  52.         }
  53.         int source;
  54.         System.out.println("Enter the source vertex");
  55.         try{
  56.             source = Integer.parseInt(br.readLine());
  57.         }catch(IOException e){
  58.             System.out.println("An error occurred");
  59.             return;
  60.         }
  61.         breadthFirstSearch(matrix,source);
  62.     }
  63. }
Program Explanation

1. In function breadthFirstSearch(), a boolean array is created and visited value of the source is set to true.
2. Then a queue is created and source vertex is added to it.
3. The loop while(!queue.isEmpty()) traverses until the queue is empty.
4. The nested loop for(i=0; i&ltmatrix.length; i++) traverses through all the neighbours of the currently polled vertex from the queue.
5. The condition if(matrix[x-1][i] == 1 && visited[i] == false) looks for all the neighbours of the currently polled vertex and adds the non-visited vertices to the queue.

advertisement
advertisement

Time Complexity: O(n2) where n is the number of elements in the array.

Runtime Test Cases
 
Case 1 (Simple Test Case):
 
Enter the number of vertices in the graph
4
Enter the adjacency matrix
1
1
1
0
1
0
0
0
1
1
1
0
0
0
0
1
Enter the source vertex
3
The breadth first order is
3
1
2
 
Case 2 (Simple Test Case - another example):
 
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
2
The breadth first order is
2
1
3

Sanfoundry Global Education & Learning Series – Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.