Most Stones Removed with Same Row or Column
LeetCode 947 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
answer = stones − components (union row with column).
ನಾನು Most Stones Removed with Same Row or Column (LeetCode 947) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Union Find / DSU ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Stones sharing a row or column are connected, and within a connected group you can remove all but one stone. So the answer is total stones minus the number of groups. Union each stone's row with its column (columns shifted past the rows).
Approach
- 1
Nodes 0..maxRow are rows; maxRow+1.. are columns.
- 2
Union each stone's row with its column.
- 3
Count roots among used nodes.
- 4
Return len(stones) − components.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
DSU on rows and columnsPythonO(n α(n)) time
class DisjointSet:
def __init__(self,n):
self.rank = [0]*(n+1)
self.parent = [i for i in range(n+1)]
def find(self,u):
if self.parent[u]==u:
return u
self.parent[u]=self.find(self.parent[u])
return self.parent[u]
def union(self,u,v):
pu,pv = self.find(u),self.find(v)
if pu==pv:
return
if self.rank[pu]<self.rank[pv]:
self.parent[pu]=pv
elif self.rank[pv]<self.rank[pu]:
self.parent[pv]=pu
elif self.rank[pv]==self.rank[pu]:
self.parent[pv]=pu
self.rank[pu]+=1
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
max_row = max(stone[0] for stone in stones)
max_col = max(stone[1] for stone in stones)
size = max_row+1+max_col+1
ds = DisjointSet(size)
nodes = set()
for row,col in stones:
colno = max_row+col+1
if ds.find(row)!=ds.find(colno):
ds.union(row,colno)
nodes.add(row)
nodes.add(colno)
components=0
for u in nodes:
if ds.parent[u]==u:
components+=1
return len(stones)-components
Most Stones Removed with Same Row or Column — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Most Stones Removed with Same Row or Column ಹಿಂದಿನ intuition ಏನು?
Stones sharing a row or column are connected, and within a connected group you can remove all but one stone. So the answer is total stones minus the number of groups. Union each stone's row with its column (columns shifted past the rows).
Most Stones Removed with Same Row or Column (LeetCode 947) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Nodes 0..maxRow are rows; maxRow+1.. are columns. 2. Union each stone's row with its column. 3. Count roots among used nodes. 4. Return len(stones) − components.
Most Stones Removed with Same Row or Column ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n α(n)). Space: O(R + C). (Accepted approach: DSU on rows and columns.)
Most Stones Removed with Same Row or Column ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Count only nodes that actually appear in some stone.