Java Program to Find Strongly Connected Components in Graphs

This Java program, displays the Strong Connected Components of graph.A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex. In particular , this means paths in each direction; a path from a to b and also a path from b to a.

Here is the source code of the Java program to display the Strong Connected Components of a graph. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
  
public class StrongConnectedComponents
{
    private int leader = 0;
    private int[] leader_node;
    private int explore[];
    private int finishing_time_of_node[];
    private int finishing_time = 1;
    private int number_of_nodes;
    private Stack<Integer> stack;
    private Map<Integer, Integer> finishing_time_map;
  
    public StrongConnectedComponents(int number_of_nodes)
    {
        this.number_of_nodes = number_of_nodes;
        leader_node = new int[number_of_nodes + 1];
        explore = new int[number_of_nodes + 1];
        finishing_time_of_node = new int[number_of_nodes + 1];
        stack = new Stack<Integer>();
        finishing_time_map = new HashMap<Integer, Integer>();
    }
  
    public void strongConnectedComponent(int adjacency_matrix[][])
    {
        for (int i = number_of_nodes; i > 0; i--)
        {
            if (explore[i] == 0)
            {
                dfs_1(adjacency_matrix, i);
            }
        }
        int rev_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
        for (int i = 1; i <= number_of_nodes; i++)
        {
            for (int j = 1; j <= number_of_nodes; j++)
            {
                if (adjacency_matrix[i][j] == 1)
                    rev_matrix[finishing_time_of_node[j]][finishing_time_of_node[i]] = adjacency_matrix[i][j];
            }
        }
  
        for (int i = 1; i <= number_of_nodes; i++)
        {
            explore[i] = 0;
            leader_node[i] = 0;
        }
  
        for (int i = number_of_nodes; i > 0; i--)
        {
            if (explore[i] == 0)
            {
                leader = i;
                dfs_2(rev_matrix, i);
            }
        }
    }
  
    public void dfs_1(int adjacency_matrix[][], int source)
    {
        explore = 1;
        stack.push(source);
        int i = 1;
        int element = source;
  
        while (!stack.isEmpty())
        {
            element = stack.peek();
            i = 1;
            while (i <= number_of_nodes)
            {
                if (adjacency_matrix[element][i] == 1 && explore[i] == 0)
                {
                    stack.push(i);
                    explore[i] = 1;
                    element = i;
                    i = 1;
                    continue;
                }
                i++;
            }
            int poped = stack.pop();
            int time = finishing_time++;
            finishing_time_of_node[poped] = time;
            finishing_time_map.put(time, poped);
        }
    }
  
    public void dfs_2(int rev_matrix[][], int source)
    {
        explore = 1;
        leader_node[finishing_time_map.get(source)] = leader;
        stack.push(source);
        int i = 1;
        int element = source;
        while (!stack.isEmpty())
        {
            element = stack.peek();
            i = 1;
            while (i <= number_of_nodes)
            {
                if (rev_matrix[element][i] == 1 && explore[i] == 0)
                {
                    if (leader_node[finishing_time_map.get(i)] == 0)
                        leader_node[finishing_time_map.get(i)] = leader;
                    stack.push(i);
                    explore[i] = 1;
                    element = i;
                    i = 1;
                    continue;
                }
                i++;
            }
            stack.pop();
        }
    }
  
    public static void main(String... arg)
    {
        int number_of_nodes;
        Scanner scanner = null;
        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();
  
            int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
            System.out.println("Enter the adjacency matrix");
            for (int i = 1; i <= number_of_nodes; i++)
                for (int j = 1; j <= number_of_nodes; j++)  
                    adjacency_matrix[i][j] = scanner.nextInt();
  
            StrongConnectedComponents strong = new StrongConnectedComponents(number_of_nodes);
            strong.strongConnectedComponent(adjacency_matrix);
  
            System.out.println("The Strong Connected Components are");
            for (int i = 1; i < strong.leader_node.length; i++)
            {
                System.out.println( "Node " + i+ "belongs to SCC"
                    + strong.finishing_time_map.get(strong.leader_node[i]));
            }
        } catch (InputMismatchException inputMismatch)
        {  
            System.out.println("Wrong Input Format");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$javac StrongConnectedComponents.java
$java StrongConnectedComponenets
Enter the number of nodes in the graph
8
Enter the adjacency matrix
0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 1 1 0 0 0
0 1 0 0 0 0 1 0
0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 1 0 0 0 0
The Strong Connected Components are
Node 1 belongs to SCC 2
Node 2 belongs to SCC 2
Node 3 belongs to SCC 8
Node 4 belongs to SCC 4
Node 5 belongs to SCC 8
Node 6 belongs to SCC 2
Node 7 belongs to SCC 2
Node 8 belongs to SCC 8

Related posts:

Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Server-Sent Events in Spring
JPA/Hibernate Persistence Context
Guide to the Fork/Join Framework in Java
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Guide to PriorityBlockingQueue in Java
Spring 5 Functional Bean Registration
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Introduction to Spring Cloud CLI
Working with Network Interfaces in Java
Giới thiệu Design Patterns
LIKE Queries in Spring JPA Repositories
Java Program to Find Number of Articulation points in a Graph
Simplify the DAO with Spring and Java Generics
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Getting a File’s Mime Type in Java
Spring NoSuchBeanDefinitionException
Service Registration with Eureka
Introduction to the Java ArrayDeque
Guide to the Java ArrayList
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Spring Data MongoDB – Indexes, Annotations and Converters
Creating a Generic Array in Java
Enum trong java
New Features in Java 15
Java 8 StringJoiner
Java Program to Implement Coppersmith Freivald’s Algorithm
Shuffling Collections In Java
Java Program to Solve Knapsack Problem Using Dynamic Programming
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Java Program to Implement Gaussian Elimination Algorithm
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path