-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path684. Redundant Connection.java
39 lines (39 loc) · 1.16 KB
/
684. Redundant Connection.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
/*
Question e find that edge for that the tree converted into graph
Find the last edge who cause cycle in the structure
boils down to find the edge for whom the cycle is forming.
*** Cycle detection but DFS use cannot be possible ***
*/
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int[] parent = new int[edges.length + 1];
Arrays.fill(parent, -1);
int[] ans = new int[2];
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
if (parent[u] == -1) parent[u] = u;
if (parent[v] == -1) parent[v] = v;
int leader_u = find(parent, u);
int leader_v = find(parent, v);
if (leader_u != leader_v) {
parent[leader_v] = leader_u;
} else {
ans = edge;
break;
}
}
return ans;
}
private int find(int[] parent, int f) {
return (parent[f] == f) ? f : find(parent, parent[f]);
}
}