Java Program to Find the Connected Components in an UnDirected Graph

This is a java program In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph. A graph that is itself connected has exactly one connected component, consisting of the whole graph.

Here is the source code of the Java Program to Find the Connected Components of an UnDirected Graph. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1.  
  2. // Sample program to find connected components of undirected graph
  3. package com.sanfoundry.graph;
  4.  
  5. import java.util.LinkedList;
  6. import java.util.Queue;
  7. import java.util.Scanner;
  8.  
  9. class CCGraph
  10. {
  11.     static final int MAXV      = 100;
  12.     static final int MAXDEGREE = 50;
  13.     public int       edges[][] = new int[MAXV + 1][MAXDEGREE];
  14.     public int       degree[]  = new int[MAXV + 1];
  15.     public int       nvertices;
  16.     public int       nedges;
  17.  
  18.     CCGraph()
  19.     {
  20.         nvertices = nedges = 0;
  21.         for (int i = 1; i <= MAXV; i++)
  22.             degree[i] = 0;
  23.     }
  24.  
  25.     void read_CCGraph(boolean directed)
  26.     {
  27.         int x, y;
  28.         Scanner sc = new Scanner(System.in);
  29.         System.out.println("Enter the number of vertices: ");
  30.         nvertices = sc.nextInt();
  31.         System.out.println("Enter the number of edges: ");
  32.         int m = sc.nextInt();
  33.         System.out.println("Enter the edges: <from> <to>");
  34.         for (int i = 1; i <= m; i++)
  35.         {
  36.             x = sc.nextInt();
  37.             y = sc.nextInt();
  38.             insert_edge(x, y, directed);
  39.         }
  40.         sc.close();
  41.     }
  42.  
  43.     void insert_edge(int x, int y, boolean directed)
  44.     {
  45.         if (degree[x] > MAXDEGREE)
  46.             System.out.printf(
  47.                     "Warning: insertion (%d, %d) exceeds max degree\n", x, y);
  48.         edges[x][degree[x]] = y;
  49.         degree[x]++;
  50.         if (!directed)
  51.             insert_edge(y, x, true);
  52.         else
  53.             nedges++;
  54.     }
  55.  
  56.     void print_CCGraph()
  57.     {
  58.         for (int i = 1; i <= nvertices; i++)
  59.         {
  60.             System.out.printf("%d: ", i);
  61.             for (int j = degree[i] - 1; j >= 0; j--)
  62.                 System.out.printf(" %d", edges[i][j]);
  63.             System.out.printf("\n");
  64.         }
  65.     }
  66. }
  67.  
  68. public class ConnectedComponents
  69. {
  70.     static final int MAXV         = 100;
  71.     static boolean   processed[]  = new boolean[MAXV];
  72.     static boolean   discovered[] = new boolean[MAXV];
  73.     static int       parent[]     = new int[MAXV];
  74.  
  75.     static void bfs(CCGraph g, int start)
  76.     {
  77.         Queue<Integer> q = new LinkedList<Integer>();
  78.         int i, v;
  79.         q.offer(start);
  80.         discovered[start] = true;
  81.         while (!q.isEmpty())
  82.         {
  83.             v = q.remove();
  84.             process_vertex(v);
  85.             processed[v] = true;
  86.             for (i = g.degree[v] - 1; i >= 0; i--)
  87.             {
  88.                 if (!discovered[g.edges[v][i]])
  89.                 {
  90.                     q.offer(g.edges[v][i]);
  91.                     discovered[g.edges[v][i]] = true;
  92.                     parent[g.edges[v][i]] = v;
  93.                 }
  94.             }
  95.         }
  96.     }
  97.  
  98.     static void initialize_search(CCGraph g)
  99.     {
  100.         for (int i = 1; i <= g.nvertices; i++)
  101.         {
  102.             processed[i] = discovered[i] = false;
  103.             parent[i] = -1;
  104.         }
  105.     }
  106.  
  107.     static void process_vertex(int v)
  108.     {
  109.         System.out.printf(" %d", v);
  110.     }
  111.  
  112.     static void connected_components(CCGraph g)
  113.     {
  114.         int c;
  115.         initialize_search(g);
  116.         c = 0;
  117.         for (int i = 1; i <= g.nvertices; i++)
  118.         {
  119.             if (!discovered[i])
  120.             {
  121.                 c++;
  122.                 System.out.printf("Component %d:", c);
  123.                 bfs(g, i);
  124.                 System.out.printf("\n");
  125.             }
  126.         }
  127.     }
  128.  
  129.     static public void main(String[] args)
  130.     {
  131.         CCGraph g = new CCGraph();
  132.         g.read_CCGraph(false);
  133.         g.print_CCGraph();
  134.         connected_components(g);
  135.     }
  136. }

Output:

$ javac ConnectedComponents.java
$ java ConnectedComponents
 
Enter the number of vertices: 
6
Enter the number of edges: 
7
Enter the edges: <from> <to>
1 2
2 3
2 4
4 5
5 6
6 3
6 4
1:  2
2:  4 3 1
3:  6 2
4:  6 5 2
5:  6 4
6:  4 3 5
Component 1: 1 2 4 3 6 5
 
Enter the number of vertices: 
6
Enter the number of edges: 
7
Enter the edges: <from> <to>
1 2
1 4
1 3
2 3
5 6
6 5
4 3
1:  3 4 2
2:  3 1
3:  4 2 1
4:  3 1
5:  6 6
6:  5 5
Component 1: 1 3 4 2
Component 2: 5 6

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.