Advertisement
HXXXXJ

547. Friend Circles

Mar 17th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.11 KB | None | 0 0
  1. class Solution {
  2.     func findCircleNum(_ M: [[Int]]) -> Int {
  3.         guard M.count > 1 else { return  M.count}
  4.         let n = M.count
  5.         let uf = UnionFind(n)
  6.         var res = 0
  7.         for i in stride(from: 0, to : n  , by: 1 ){
  8.             for j in stride(from: i + 1 , to : n , by: 1 ){
  9.                 if i == j {continue}
  10.                 if M[i][j] == 1 {
  11.                     uf.union(i, j)
  12.                 }
  13.             }
  14.         }
  15.        
  16.         return uf.count
  17.     }
  18. }
  19.  
  20. class UnionFind{
  21.     var father : [Int]
  22.     var count : Int
  23.     init(_ n : Int){
  24.         count = n
  25.         father = [Int](repeating: 0 , count : n)
  26.         for i in 0 ..< n {
  27.             father[i] = i
  28.         }
  29.     }
  30.     func find(_ x : Int) -> Int{
  31.         if father[x] == x {
  32.             return x
  33.         }
  34.         let root_x = find(father[x])
  35.         father[x] = root_x
  36.         return root_x
  37.     }
  38.    
  39.     func union(_ x : Int, _ y : Int){
  40.         let root_x = find(x)
  41.         let root_y = find(y)
  42.         if root_x == root_y {return }
  43.         count -= 1
  44.         father[root_x] = root_y
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement