并查集,看图中有多少连通分量。删除最多可以是每个连通分量里只剩一个石子。所以总的减去连通分量的个数就是答案
class Solution(object):
def removeStones(self, stones):
"""
:type stones: List[List[int]]
:rtype: int
"""
n = len(stones)
self.count = n
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(i,j):
if find(i) != find(j):
parent[find(i)] = find(j)
self.count -= 1
for i in range(n):
for j in range(i+1,n):
if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]:
union(i,j)
return n - self.count
把行列转化成相同的维度
def removeStones(self, stones):
"""
:type stones: List[List[int]]
:rtype: int
"""
n = len(stones)
self.count = 0
self.parent = {}
def find(x):
if x not in self.parent:
self.count += 1
self.parent[x] = x
if self.parent[x] != x:
self.parent[x] = find(self.parent[x])
return self.parent[x]
def union(i,j):
if find(i) != find(j):
self.parent[find(i)] = find(j)
self.count -= 1
for i in stones:
union(i[0]+10001,i[1])
return n - self.count