0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #947: Most Stones Removed with Same Row or Column

Posted at
func removeStones(_ stones: [[Int]]) -> Int {
    var xDict = [Int: [Int]]()
    var yDict = [Int: [Int]]()
    for stone in stones {
        xDict[stone[0], default:[]].append(stone[1])
        yDict[stone[1], default:[]].append(stone[0])
    }
    var visited = Set<[Int]>()
    var answer = 0
    for stone in stones {
        var count = 0
        if !visited.contains([stone[0], stone[1]]) {
            var xArr = [stone[0]]
            var yArr = [stone[1]]
            while !xArr.isEmpty || !yArr.isEmpty {
                if !xArr.isEmpty {
                    let x = xArr.removeFirst()
                    let ar = xDict[x]!
                    for num in ar {
                        if !visited.contains([x, num]) {
                            yArr.append(num)
                            count += 1
                            visited.insert([x,num])
                        }
                    }
                }
                if !yArr.isEmpty {
                    let y = yArr.removeFirst()
                    let ar = yDict[y]!
                    for num in ar {
                        if !visited.contains([num, y]) {
                            xArr.append(num)
                            count += 1
                            visited.insert([num,y])
                        }
                    }
                }
            }
            count -= 1
        }
        answer += count
    }
    return answer
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?