forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStronglyConnectedComponentOptimized.java
86 lines (75 loc) · 2.78 KB
/
StronglyConnectedComponentOptimized.java
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
package com.thealgorithms.graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
/**
* Finds the strongly connected components in a directed graph.
*
* @param adjList The adjacency list representation of the graph.
* @param n The number of nodes in the graph.
* @return The number of strongly connected components.
*/
public class StronglyConnectedComponentOptimized {
public void btrack(HashMap<Integer, List<Integer>> adjList, int[] visited, Stack<Integer> dfsCallsNodes, int currentNode) {
visited[currentNode] = 1;
List<Integer> neighbors = adjList.get(currentNode);
// Check for null before iterating
if (neighbors != null) {
for (int neighbor : neighbors) {
if (visited[neighbor] == -1) {
btrack(adjList, visited, dfsCallsNodes, neighbor);
}
}
}
dfsCallsNodes.add(currentNode);
}
public void btrack2(HashMap<Integer, List<Integer>> adjRevList, int[] visited, int currentNode, List<Integer> newScc) {
visited[currentNode] = 1;
newScc.add(currentNode);
List<Integer> neighbors = adjRevList.get(currentNode);
// Check for null before iterating
if (neighbors != null) {
for (int neighbor : neighbors) {
if (visited[neighbor] == -1) {
btrack2(adjRevList, visited, neighbor, newScc);
}
}
}
}
public int getOutput(HashMap<Integer, List<Integer>> adjList, int n) {
int[] visited = new int[n];
Arrays.fill(visited, -1);
Stack<Integer> dfsCallsNodes = new Stack<>();
for (int i = 0; i < n; i++) {
if (visited[i] == -1) {
btrack(adjList, visited, dfsCallsNodes, i);
}
}
HashMap<Integer, List<Integer>> adjRevList = new HashMap<>();
for (int i = 0; i < n; i++) {
adjRevList.put(i, new ArrayList<>());
}
for (int i = 0; i < n; i++) {
List<Integer> neighbors = adjList.get(i);
// Check for null before iterating
if (neighbors != null) {
for (int neighbor : neighbors) {
adjRevList.get(neighbor).add(i);
}
}
}
Arrays.fill(visited, -1);
int stronglyConnectedComponents = 0;
while (!dfsCallsNodes.isEmpty()) {
int node = dfsCallsNodes.pop();
if (visited[node] == -1) {
List<Integer> newScc = new ArrayList<>();
btrack2(adjRevList, visited, node, newScc);
stronglyConnectedComponents++;
}
}
return stronglyConnectedComponents;
}
}