Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
- let uf = UnionFind(n)
- for edge in edges{
- uf.union(edge[0], edge[1])
- }
- return uf.count
- }
- }
- class UnionFind{
- var father : [Int]
- var count : Int
- init(_ n : Int){
- count = n
- father = [Int](repeating: 0 , count : n)
- for i in 0 ..< n {
- father[i] = i
- }
- }
- func find(_ x : Int) -> Int{
- if father[x] == x {
- return x
- }
- let root_x = find(father[x])
- father[x] = root_x
- return root_x
- }
- func union(_ x : Int, _ y : Int){
- let root_x = find(x)
- let root_y = find(y)
- if root_x == root_y {return }
- count -= 1
- father[root_x] = root_y
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement