Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 26f0805

Browse files
authored
Merge pull request #965 from MaratKhakim/684-Redundant-Connection-kt
Kotlin: 684. Redundant Connection
2 parents f4f43a5 + fc0b766 commit 26f0805

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

kotlin/684-Redundant-Connection.kt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
fun findRedundantConnection(edges: Array<IntArray>): IntArray {
3+
val uf = UnionFind(edges.size)
4+
5+
for (edge in edges) {
6+
val (u, v) = edge
7+
8+
if (uf.isConnected(u-1, v-1))
9+
return intArrayOf(u, v)
10+
11+
uf.unify(u-1, v-1)
12+
}
13+
14+
return intArrayOf(0)
15+
}
16+
}
17+
18+
class UnionFind(n : Int) {
19+
val parent = IntArray(n) { it }
20+
val rank = IntArray(n) { 1 }
21+
22+
fun unify(p: Int, q: Int) {
23+
val rootP = find(p)
24+
val rootQ = find(q)
25+
26+
if (rootP == rootQ)
27+
return
28+
29+
if (rank[rootP] > rank[rootQ]) {
30+
parent[rootQ] = parent[rootP]
31+
rank[rootP] += rank[rootQ]
32+
} else {
33+
parent[rootP] = parent[rootQ]
34+
rank[rootQ] += rank[rootP]
35+
}
36+
}
37+
38+
fun find(p: Int): Int {
39+
var root = p
40+
var curr = p
41+
42+
while (root != parent[root])
43+
root = parent[root]
44+
45+
while (root != curr) {
46+
val next = parent[curr]
47+
parent[p] = parent[root]
48+
curr = next
49+
}
50+
51+
return root
52+
}
53+
54+
fun isConnected(p: Int, q: Int): Boolean {
55+
return find(p) == find(q)
56+
}
57+
}

0 commit comments

Comments
 (0)