forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphValidTree.swift
43 lines (35 loc) · 1.01 KB
/
GraphValidTree.swift
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
/**
* Question Link: https://leetcode.com/problems/graph-valid-tree/
* Primary idea: Classic Union Find, return false encountering a cycle,
* or finally there is more than one link
*
* Time Complexity: O(nlogn), Space Complexity: O(n)
*
*/
class GraphValidTree {
func validTree(_ n: Int, _ edges: [[Int]]) -> Bool {
guard n > 0 else {
return true
}
var roots = [Int](0..<n)
var count = n
for edge in edges {
let root0 = findRoot(edge[0], roots)
let root1 = findRoot(edge[1], roots)
if root0 == root1 {
return false
} else {
roots[root1] = root0
count -= 1
}
}
return count == 1
}
private func findRoot(_ node: Int, _ roots: [Int]) -> Int {
var node = node
while node != roots[node] {
node = roots[node]
}
return node
}
}