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
思路:比赛用union-find,Python TLE,后来才发现额外自作聪明
if xi==xj or yi==yj or (xi,yj) in s or (xj,yi) in s:
union(i,j)
增加了union的次数,其实只要下面这样就行了
if xi==xj or yi==yj:
union(i,j)
(一开始想路径压缩,但是Python不好用tail recursion,路径压缩会爆栈),anyway,去掉冗余的union之后就可以A了
class Solution:
def removeStones(self, stones):
"""
:type stones: List[List[int]]
:rtype: int
"""
n=len(stones)
fa=list(range(n+1))
def find(i):
while fa[i]!=i:
fa[i]=fa[fa[i]]
i=fa[i]
return i
def union(i,j):
fi=find(i)
fj=find(j)
fa[fi]=fj
s=set([tuple(t) for t in stones])
for i in range(n):
for j in range(i+1,n):
xi,yi=stones[i]
xj,yj=stones[j]
if xi==xj or yi==yj:
union(i,j)
d={}
for i in range(n):
fi=find(i)
d[fi]=d.get(fi,0)+1
res=0
for i in d:
res+=d[i]-1
return res
s=Solution()
print(s.removeStones([[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]))
print(s.removeStones([[0,0],[0,2],[1,1],[2,0],[2,2]]))
print(s.removeStones([[0,0]]))
上面复杂度NNlogN,其实可以先求出连接矩阵,然后BFS一遍,可以做到NN(BFS过程每个点都要遍历一遍连接的其他点),但也要去掉冗余的连接才不会TLE
class Solution:
def removeStones(self, stones):
"""
:type stones: List[List[int]]
:rtype: int
"""
from collections import defaultdict
n=len(stones)
adj=defaultdict(set)
for i in range(n):
for j in range(i+1,n):
xi,yi=stones[i]
xj,yj=stones[j]
if xi==xj or yi==yj:
adj[i].add(j)
adj[j].add(i)
marked=[False]*n
res=0
for i in range(n):
if marked[i]: continue
q=[i]
marked[i]=True
while q:
s=q.pop()
for t in adj[s]:
if marked[t]: continue
marked[t]=True
q.append(t)
res+=1
return n-res
s=Solution()
print(s.removeStones([[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]))
print(s.removeStones([[0,0],[0,2],[1,1],[2,0],[2,2]]))
print(s.removeStones([[0,0]]))