forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path684-Redundant-Connection.c
More file actions
35 lines (31 loc) · 844 Bytes
/
684-Redundant-Connection.c
File metadata and controls
35 lines (31 loc) · 844 Bytes
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
/*
Return an edge that can be removed so that the resulting graph is a tree of n nodes.
Time: O(n)
Space: O(n)
*/
int max(int a, int b) {
return a>b?a:b;
}
int find(int* parent, int k) {
if (parent[k]==k)
return k;
return find(parent, parent[k]);
}
int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){
int* ans = malloc(sizeof(int)*2);
int* parent = malloc(sizeof(int)*(edgesSize+1));
for (int i=0; i<=edgesSize; i++)
parent[i] = i;
for (int i=0; i<edgesSize; i++) {
int f1 = find(parent, edges[i][0]);
int f2 = find(parent, edges[i][1]);
if (f1==f2) {
ans[0] = edges[i][0];
ans[1] = edges[i][1];
} else { // Union
parent[f1] = f2;
}
}
*returnSize = 2;
return ans;
}