On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
총 5개 제거가 가능하다.
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
rows = {}
cols = {}
for row, col in stones:
if row not in rows:
rows[row] = []
if col not in cols:
cols[col] = []
rows[row].append((row, col))
cols[col].append((row, col))
visited = set()
def dfs(row, col):
if (row, col) not in visited:
visited.add((row, col))
for r, c in rows[row]:
dfs(r, c)
for r, c in cols[col]:
dfs(r, c)
count = 0
for row, col in stones:
if (row, col) not in visited:
dfs(row, col)
count += 1
return len(stones) - count