Java Program to Check the Connectivity of Graph Using BFS

This is a Java Program to implment graph and check the connectivity between nodes using a standard Breadth First Search algorithm. Algorithm visits the node that was traversed first or appeared in liked list representation of the node or first come first serve basis. We create a vistied array to avoid revisiting a node. If destination node appears in visited array, source and destination nodes are connected, not otherwise.

Here is the source code of the Java Program to Check the Connectivity of Graph Using BFS. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a java program to check the nodes are connected using BFS
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. import java.util.Scanner;
  5.  
  6. public class Connectivity_BFS
  7. {
  8.     private final int      vertices;
  9.     private int[][]        adjacency_matrix;
  10.     private Queue<Integer> queue;
  11.  
  12.     public Connectivity_BFS(int v)
  13.     {
  14.         vertices = v;
  15.         adjacency_matrix = new int[vertices + 1][vertices + 1];
  16.         queue = new LinkedList<Integer>();
  17.     }
  18.  
  19.     public void makeEdge(int to, int from, int edge)
  20.     {
  21.         try
  22.         {
  23.             adjacency_matrix[to][from] = edge;
  24.             adjacency_matrix[from][to] = edge;
  25.         } catch (ArrayIndexOutOfBoundsException index)
  26.         {
  27.             System.out.println("The vertices does not exists");
  28.         }
  29.     }
  30.  
  31.     public int getEdge(int to, int from)
  32.     {
  33.         try
  34.         {
  35.             return adjacency_matrix[to][from];
  36.         } catch (ArrayIndexOutOfBoundsException index)
  37.         {
  38.             System.out.println("The vertices does not exists");
  39.         }
  40.         return -1;
  41.     }
  42.  
  43.     public void bfs(int source)
  44.     {
  45.         int number_of_nodes = adjacency_matrix[source].length - 1;
  46.         int[] visited = new int[number_of_nodes + 1];
  47.         int i, element;
  48.         visited[source] = 1;
  49.         queue.add(source);
  50.         while (!queue.isEmpty())
  51.         {
  52.             element = queue.remove();
  53.             i = 1;// element;
  54.             while (i <= number_of_nodes)
  55.             {
  56.                 if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
  57.                 {
  58.                     queue.add(i);
  59.                     visited[i] = 1;
  60.                 }
  61.                 i++;
  62.             }
  63.         }
  64.  
  65.         System.out.print("The source node " + source + " is connected to: ");
  66.         int count = 0;
  67.         for (int v = 1; v <= number_of_nodes; v++)
  68.             if (visited[v] == 1)
  69.             {
  70.                 System.out.print(v + " ");
  71.                 count++;
  72.             }
  73.  
  74.         if (count == number_of_nodes)
  75.             System.out.print("\nThe Graph is Connected ");
  76.         else
  77.             System.out.print("\nThe Graph is Disconnected ");
  78.     }
  79.  
  80.     public static void main(String args[])
  81.     {
  82.         int v, e, count = 1, to = 0, from = 0;
  83.         Scanner sc = new Scanner(System.in);
  84.         Connectivity_BFS graph;
  85.         System.out.println("The Undirected Graph Connectivity Test");
  86.         try
  87.         {
  88.             System.out.println("Enter the number of vertices: ");
  89.             v = sc.nextInt();
  90.             System.out.println("Enter the number of edges: ");
  91.             e = sc.nextInt();
  92.  
  93.             graph = new Connectivity_BFS(v);
  94.  
  95.             System.out.println("Enter the edges: <to> <from>");
  96.             while (count <= e)
  97.             {
  98.                 to = sc.nextInt();
  99.                 from = sc.nextInt();
  100.  
  101.                 graph.makeEdge(to, from, 1);
  102.                 count++;
  103.             }
  104.  
  105.             System.out.println("The adjacency matrix for the given graph is: ");
  106.             System.out.print("  ");
  107.             for (int i = 1; i <= v; i++)
  108.                 System.out.print(i + " ");
  109.             System.out.println();
  110.  
  111.             for (int i = 1; i <= v; i++)
  112.             {
  113.                 System.out.print(i + " ");
  114.                 for (int j = 1; j <= v; j++)
  115.                     System.out.print(graph.getEdge(i, j) + " ");
  116.                 System.out.println();
  117.             }
  118.  
  119.             System.out.println("Enter the Source Node: ");
  120.             int sourceNode = sc.nextInt();
  121.             graph.bfs(sourceNode);
  122.  
  123.         } catch (Exception E)
  124.         {
  125.             System.out.println("Something went wrong");
  126.         }
  127.  
  128.         sc.close();
  129.     }
  130. }

Output:

$ javac Connectivity_BFS.java
$ java Connectivity_BFS
 
The Undirected Graph Connectivity Test(BFS)
Enter the number of vertices: 
4
Enter the number of edges: 
2
Enter the edges: <to> <from>
1 2
3 4
The adjacency matrix for the given graph is: 
  1 2 3 4 
1 0 1 0 0 
2 1 0 0 0 
3 0 0 0 1 
4 0 0 1 0 
Enter the Source Node: 
3
The source node 3 is connected to: 3 4 
The Graph is Disconnected 
 
The Undirected Graph Connectivity Test(BFS)
Enter the number of vertices: 
4
Enter the number of edges: 
5
Enter the edges: <to> <from>
1 2
2 3
3 4
1 4
1 3
The adjacency matrix for the given graph is: 
  1 2 3 4 
1 0 1 1 1 
2 1 0 1 0 
3 1 1 0 1 
4 1 0 1 0 
Enter the Source Node: 
4
The source node 4 is connected to: 1 2 3 4 
The Graph is Connected

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

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.