|
| 1 | +class DisjointSet { |
| 2 | + private var ranks: [Int] |
| 3 | + private var roots: [Int] |
| 4 | + |
| 5 | + init(numVertices: Int) { |
| 6 | + ranks = [Int](repeating: 0, count: numVertices) |
| 7 | + roots = [Int](repeating: 0, count: numVertices) |
| 8 | + |
| 9 | + for i in 0..<numVertices { |
| 10 | + roots[i] = i |
| 11 | + ranks[i] = 1 |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + public func union(v1 x: Int, v2 y: Int) { |
| 16 | + let rootX = find(of: x) |
| 17 | + let rootY = find(of: y) |
| 18 | + |
| 19 | + guard rootX != rootY else { return } |
| 20 | + |
| 21 | + let rankX = ranks[rootX] |
| 22 | + let rankY = ranks[rootY] |
| 23 | + |
| 24 | + if rankX > rankY { // go into X |
| 25 | + roots[rootY] = rootX |
| 26 | + } else if rankY > rankX { // go into Y |
| 27 | + roots[rootX] = rootY |
| 28 | + } else { // go into X by default |
| 29 | + roots[rootY] = rootX |
| 30 | + ranks[rootX] += 1 |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + private func find(of x: Int) -> Int { |
| 35 | + if roots[x] == x { return x } |
| 36 | + roots[x] = find(of: roots[x]) |
| 37 | + return roots[x] |
| 38 | + } |
| 39 | + |
| 40 | + public func areConnected(v1: Int, v2: Int) -> Bool { |
| 41 | + find(of: v1) == find(of: v2) |
| 42 | + } |
| 43 | + |
| 44 | + public func areDisjoint(v1: Int, v2: Int) -> Bool { |
| 45 | + !areConnected(v1: v1, v2: v2) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +class Solution { |
| 50 | + func validTree(_ n: Int, _ edges: [[Int]]) -> Bool { |
| 51 | + // Check if n-1 edges |
| 52 | + let numEdges = edges.count |
| 53 | + guard numEdges == (n - 1) else { return false } |
| 54 | + |
| 55 | + // Check if connected => Can use DisjointSet/UnionFind |
| 56 | + let ds = DisjointSet(numVertices: n) |
| 57 | + for edge in edges { |
| 58 | + let v1 = edge[0]; let v2 = edge[1] |
| 59 | + guard ds.areDisjoint(v1: v1, v2: v2) else { |
| 60 | + return false |
| 61 | + } |
| 62 | + ds.union(v1: v1, v2: v2) |
| 63 | + } |
| 64 | + |
| 65 | + return true; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | + |
0 commit comments