leetcode 947移走最多的石头

题目:
On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.

Now, a move consists of removing a stone that shares a column or row with another stone on the grid.

What is the largest possible number of moves we can make?

Example 1:

Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2:

Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3:

Input: stones = [[0,0]]
Output: 0

Note:

1 <= stones.length <= 1000
0 <= stones[i][j] < 10000
解法一:
深度优先搜索
这其实就是个在无向图中统计连通分量个数的问题,最终的结果应该为坐标个数总数减去连通分量个数
有了以上思路,我们需要对输入的数据进行一些处理,根据输入将其转为无向邻接表存储
def removeStones(self, stones):
“”"
:type stones: List[List[int]]
:rtype: int
“”"
graph=collections.defaultdict(list)
for i,x in enumerate(stones):
for j in range(i):
y=stones[j]
if x[0]==y[0] or x[1]==y[1]:
graph[i].append(j)
graph[j].append(i)
N,ans=len(stones),0
seen=[False]*N
for i in range(N):
if not seen[i]:
stack,seen[i]=[i],True
while stack:
ans,node=ans+1,stack.pop()
for nei in graph[node]:
if not seen[nei]:
stack.append(nei)
seen[nei]=True
ans-=1
return ans
时间复杂度:O(N^2)
空间复杂度:O(N)
方法二:
使用并查集,我们将二维的坐标进行降维处理,使得横坐标在【0,10000】范围内,而纵坐标在[10001,20000]范围内,对于每对坐标都使其连在一起,这样的话当有横坐标或者纵坐标相同的时候便会连在同一个集合里面
class DSU:
def init(self,n):
self.p=range(n)
def find(self,x):
if self.p[x]!=x:
self.p[x]=self.find(self.p[x])
return self.p[x]
def union(self,x,y):
xr=self.find(x)
yr=self.find(y)
self.p[xr]=yr
class Solution(object):
def removeStones(self, stones):
“”"
:type stones: List[List[int]]
:rtype: int
“”"
dsu=DSU(20000)
for x,y in stones:
dsu.union(x,y+10000)
return len(stones)-len({dsu.find(x) for x,y in stones})
时间复杂度:O(N)
空间复杂度:O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值