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