class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
index = collections.defaultdict(set)
for i, j in stones:
index[i].add(j+10000)
index[j+10000].add(i)
seen = set()
islands = 0
def dfs(i):
seen.add(i)
for j in index[i]:
if j not in seen:
dfs(j)
for i,j in stones:
if i not in seen:
dfs(i) #i里的cols 全部相连
dfs(j+10000)#i里的rows 全部相连
islands += 1
return len(stones) - islands
Union Find
UNION FIND (i,~j)也是,等于把j映射到j+10000。~j是补码,就是二进制code倒过来。
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
f = {}
def find(x):
if f[x]!=x:
f[x] = find(f[x])
return f[x]
def union(x,y):
f.setdefault(x,x)
f.setdefault(y,y)
f[find(x)] = find(y)
for x,y in stones:
union(x,~y)
return len(stones) - len({find(x) for x in f})#点数-岛数