947. Most Stones Removed with Same Row or Column
阿新 • • 發佈:2018-12-02
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]]))