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
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme