Advertisement
HXXXXJ

323. Number of Connected Components in an Undirected Graph

Mar 17th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.84 KB | None | 0 0
  1. class Solution {
  2.     func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
  3.         let uf = UnionFind(n)
  4.         for edge in edges{
  5.             uf.union(edge[0], edge[1])
  6.            
  7.         }
  8.         return uf.count
  9.     }
  10. }
  11. class UnionFind{
  12.     var father : [Int]
  13.     var count : Int
  14.     init(_ n : Int){
  15.         count = n
  16.         father = [Int](repeating: 0 , count : n)
  17.         for i in 0 ..< n {
  18.             father[i] = i
  19.         }
  20.     }
  21.     func find(_ x : Int) -> Int{
  22.         if father[x] == x {
  23.             return x
  24.         }
  25.         let root_x = find(father[x])
  26.         father[x] = root_x
  27.         return root_x
  28.     }
  29.    
  30.     func union(_ x : Int, _ y : Int){
  31.         let root_x = find(x)
  32.         let root_y = find(y)
  33.         if root_x == root_y {return }
  34.         count -= 1
  35.         father[root_x] = root_y
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement