- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
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
packagecom.thealgorithms.graph;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.List;
importjava.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.
*/
publicclassStronglyConnectedComponentOptimized {
publicvoidbtrack(HashMap<Integer, List<Integer>> adjList, int[] visited, Stack<Integer> dfsCallsNodes, intcurrentNode) {
visited[currentNode] = 1;
List<Integer> neighbors = adjList.get(currentNode);
// Check for null before iterating
if (neighbors != null) {
for (intneighbor : neighbors) {
if (visited[neighbor] == -1) {
btrack(adjList, visited, dfsCallsNodes, neighbor);
}
}
}
dfsCallsNodes.add(currentNode);
}
publicvoidbtrack2(HashMap<Integer, List<Integer>> adjRevList, int[] visited, intcurrentNode, List<Integer> newScc) {
visited[currentNode] = 1;
newScc.add(currentNode);
List<Integer> neighbors = adjRevList.get(currentNode);
// Check for null before iterating
if (neighbors != null) {
for (intneighbor : neighbors) {
if (visited[neighbor] == -1) {
btrack2(adjRevList, visited, neighbor, newScc);
}
}
}
}
publicintgetOutput(HashMap<Integer, List<Integer>> adjList, intn) {
int[] visited = newint[n];
Arrays.fill(visited, -1);
Stack<Integer> dfsCallsNodes = newStack<>();
for (inti = 0; i < n; i++) {
if (visited[i] == -1) {
btrack(adjList, visited, dfsCallsNodes, i);
}
}
HashMap<Integer, List<Integer>> adjRevList = newHashMap<>();
for (inti = 0; i < n; i++) {
adjRevList.put(i, newArrayList<>());
}
for (inti = 0; i < n; i++) {
List<Integer> neighbors = adjList.get(i);
// Check for null before iterating
if (neighbors != null) {
for (intneighbor : neighbors) {
adjRevList.get(neighbor).add(i);
}
}
}
Arrays.fill(visited, -1);
intstronglyConnectedComponents = 0;
while (!dfsCallsNodes.isEmpty()) {
intnode = dfsCallsNodes.pop();
if (visited[node] == -1) {
List<Integer> newScc = newArrayList<>();
btrack2(adjRevList, visited, node, newScc);
stronglyConnectedComponents++;
}
}
returnstronglyConnectedComponents;
}
}