@@ -15,9 +15,14 @@ public class StronglyConnectedComponentOptimized {
15
15
16
16
public void btrack (HashMap <Integer , List <Integer >> adjList , int [] visited , Stack <Integer > dfsCallsNodes , int currentNode ) {
17
17
visited [currentNode ] = 1 ;
18
- for (int neighbor : adjList .get (currentNode )) {
19
- if (visited [neighbor ] == -1 ) {
20
- btrack (adjList , visited , dfsCallsNodes , neighbor );
18
+ List <Integer > neighbors = adjList .get (currentNode );
19
+
20
+ // Check for null before iterating
21
+ if (neighbors != null ) {
22
+ for (int neighbor : neighbors ) {
23
+ if (visited [neighbor ] == -1 ) {
24
+ btrack (adjList , visited , dfsCallsNodes , neighbor );
25
+ }
21
26
}
22
27
}
23
28
dfsCallsNodes .add (currentNode );
@@ -26,9 +31,14 @@ public void btrack(HashMap<Integer, List<Integer>> adjList, int[] visited, Stack
26
31
public void btrack2 (HashMap <Integer , List <Integer >> adjRevList , int [] visited , int currentNode , List <Integer > newScc ) {
27
32
visited [currentNode ] = 1 ;
28
33
newScc .add (currentNode );
29
- for (int neighbor : adjRevList .get (currentNode )) {
30
- if (visited [neighbor ] == -1 ) {
31
- btrack2 (adjRevList , visited , neighbor , newScc );
34
+ List <Integer > neighbors = adjRevList .get (currentNode );
35
+
36
+ // Check for null before iterating
37
+ if (neighbors != null ) {
38
+ for (int neighbor : neighbors ) {
39
+ if (visited [neighbor ] == -1 ) {
40
+ btrack2 (adjRevList , visited , neighbor , newScc );
41
+ }
32
42
}
33
43
}
34
44
}
@@ -50,8 +60,12 @@ public int getOutput(HashMap<Integer, List<Integer>> adjList, int n) {
50
60
}
51
61
52
62
for (int i = 0 ; i < n ; i ++) {
53
- for (int neighbor : adjList .get (i )) {
54
- adjRevList .get (neighbor ).add (i );
63
+ List <Integer > neighbors = adjList .get (i );
64
+ // Check for null before iterating
65
+ if (neighbors != null ) {
66
+ for (int neighbor : neighbors ) {
67
+ adjRevList .get (neighbor ).add (i );
68
+ }
55
69
}
56
70
}
57
71
@@ -69,5 +83,4 @@ public int getOutput(HashMap<Integer, List<Integer>> adjList, int n) {
69
83
70
84
return stronglyConnectedComponents ;
71
85
}
72
-
73
86
}
0 commit comments