class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
n = len(stones)
if n == 1:
return 0
parents = {}
def find(x):
if x not in parents:
parents[x] = x
if x != parents[x]:
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
x = find(x)
y = find(y)
if x < y:
parents[y] = x
else:
parents[x] = y
for i in range(n):
find(i)
for i in range(n):
for j in range(i):
if stones[i][0] == stones[j][0]:
union(i, j)
if stones[i][1] == stones[j][1]:
union(i, j)
for i in range(n):
find(i)
return len(parents) - len(set(parents.values()))