Advertisement
HXXXXJ

947. Most Stones Removed with Same Row or Column

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