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
| class Solution { int time = 0; List<List<Integer>> res = new ArrayList<>();
public void dfs(int u, List<List<Integer>> graph, int[] disc, int[] low, int[] parent, boolean[] visited){ visited[u] = true; disc[u] = low[u] = ++ time; for (int v : graph.get(u)){ if (!visited[v]){ parent[v] = u; dfs(v, graph, disc, low, parent,visited); low[u] = Math.min(low[u], low[v]); if (low[v] > disc[u]){ List<Integer> tmp = new ArrayList<>(); tmp.add(u); tmp.add(v); res.add(tmp); } } else{ if (v != parent[u]){ low[u] = Math.min(low[u], disc[v]); } } } } public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++){ graph.add(new ArrayList<Integer>()); } for (List<Integer> pair : connections){ int u = pair.get(0); int v = pair.get(1); graph.get(u).add(v); graph.get(v).add(u); } boolean[] visited = new boolean[n]; int[] disc = new int[n]; int[] low = new int[n]; int[] parent = new int[n]; for (int i = 0 ; i < n; i++){ visited[i] = false; parent[i] = -1; } dfs(0, graph, disc, low, parent,visited); return res; } }
|