-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindAllCriticalConnectionsInTheGraph.java
67 lines (59 loc) · 1.53 KB
/
FindAllCriticalConnectionsInTheGraph.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
//User function Template for Java
class Solution
{
public ArrayList<ArrayList<Integer>> criticalConnections(int v, ArrayList<ArrayList<Integer>> adj)
{
// Code here
boolean visited[] = new boolean[v];
int parent = -1;
int disc[] = new int[v];
int low[] = new int[v];
int timer = 0;
Arrays.fill(disc, -1);
Arrays.fill(low, -1);
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
for(int i=0;i<v;i++) {
if(!visited[i]) {
dfs(i,parent,timer,disc,low,ans,visited,adj);
}
}
//sort
for(ArrayList<Integer> a : ans){
Collections.sort(a);
}
Collections.sort(ans,new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> a,ArrayList<Integer> b) {
if((a.get(0)-b.get(0))==0){
return a.get(1)-b.get(1);
}
return a.get(0)-b.get(0);
}
});
return ans;
}
private static void dfs(int node, int parent, int timer, int[] disc, int[] low, ArrayList<ArrayList<Integer>> ans,
boolean[] visited, ArrayList<ArrayList<Integer>> list) {
visited[node] = true;
disc[node] = timer;
low[node] = timer;
timer++;
for(Integer val : list.get(node)) {
if(val == parent) {
continue;
}
if(!visited[val]) {
dfs(val, node, timer, disc, low, ans, visited, list);
low[node] = Math.min(low[node],low[val]);
if(low[val]>disc[node]) {
ArrayList<Integer> a = new ArrayList<>();
a.add(node);
a.add(val);
ans.add(a);
}
} else {
low[node] = Math.min(low[node], disc[val]);
}
}
}
}