题目中要求我们去看看是否有同行,同列,我们可以尝试遍历所有进行比较,再添加一个参数去计算,但是这个复杂度有点高,我们是否可以用另一种方法进行遍历比较?
我们可以尝试用并查集进行问题的解决,如何解决?我们分别比较所有,有相同的就连接起来,并且参数会加1(删去一个元素),那我们可以直接用代码:
class UnionFind:
def __init__(self):
"""
记录每个节点的父节点
"""
self.father = {}
self.count = 0
def find(self, x):
"""
查找根节点
路径压缩
"""
root = x
while self.father[root] != None:
root = self.father[root]
# 路径压缩
while x != root:
original_father = self.father[x]
self.father[x] = root
x = original_father
return root
def merge(self, x, y):
"""
合并两个节点
"""
root_x, root_y = self.find(x), self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
self.count += 1
def add(self, x):
"""
添加新节点
"""
if x not in self.father:
self.father[x] = None
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
n = len(stones)
x = UnionFind()
for i in range(n):
x.add(i)
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]:
x.merge(i, j)
return x.count
并查集讲解如下:
https://blog.csdn.net/qq_51718832/article/details/112340746