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
| class Solution {
// Brute Force, many DFS , O(E * (N + E)) Time Limit Exceeded
public List<List<Integer>> criticalConnections2(int n, List<List<Integer>> connections) {
List<List<Integer>> res = new ArrayList<>();
for (int skip = 0; skip < connections.size(); skip++) {
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs1(i, skip, connections, visited);
count++;
}
}
if (count != 1) {
res.add(connections.get(skip));
}
}
return res;
}
void dfs1(int i, int skip, List<List<Integer>> connections, boolean[] visited) {
visited[i] = true;
for (int edgeIndex = 0; edgeIndex < connections.size(); edgeIndex++) {
if (edgeIndex == skip) continue;
List<Integer> edge = connections.get(edgeIndex);
int a = edge.get(0);
int b = edge.get(1);
if (a == i && !visited[b]) {
dfs1(b, skip, connections, visited);
}
if (b == i && !visited[a]) {
dfs1(a, skip, connections, visited);
}
}
}
List<Integer>[] G;
int[] disc;
int[] low;
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
disc = new int[n];
low = new int[n];
G = build(n, connections);
dfs(0, -1, 1);
return res;
}
void dfs(int node, int parent, int time) {
disc[node] = time;
low[node] = time;
for (int n : G[node]) {
if (n == parent) continue;
if (disc[n] == 0) {
dfs(n, node, ++time);
}
low[node] = Math.min(low[node], low[n]);
if (disc[node] < low[n]) {
res.add(Arrays.asList(node, n));
}
}
}
List<Integer>[] build(int n, List<List<Integer>> connections) {
G = new List[n];
for (int i = 0; i < n; i++) {
G[i] = new ArrayList<>();
}
for (var con: connections) {
G[con.get(0)].add(con.get(1));
G[con.get(1)].add(con.get(0));
}
return G;
}
}
|