Most Stones Removed with Same Row or Column LeetCode solution in Python

1
# Runtime: 187 ms (Top 84.32%) | Memory: 18.9 MB (Top 5.06%)
2
class Solution:
3
def removeStones(self, stones: List[List[int]]) -> int:
4
def dfs(row, col):
5
if seen[(row, col)]:
6
return 0
7
seen[(row, col)] = True
8
for r, c in tableRow[row]:
9
dfs(r, c)
10
for r, c in tableCol[col]:
11
dfs(r, c)
12
return 1
13

14
tableRow, tableCol = {}, {}
15
for row, col in stones:
16
if row not in tableRow:
17
tableRow[row] = set()
18
if col not in tableCol:
19
tableCol[col] = set()
20
tableRow[row].add((row, col))
21
tableCol[col].add((row, col))
22

23
count, seen = 0, {(row, col): False for row, col in stones}
24
for row, col in stones:
25
count += dfs(row, col)
26
return abs(len(stones) - count)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0