herrDeng網內搜尋

自訂搜尋

Ads

2025年1月31日 星期五

C++ UnionFind解難題Leetcdoe 827 Making A Large Island(含Py3解)


C++ UnionFind解難題Leetcdoe 827  Making A Large Island
嘗試UnionFind解決。由於該題目透過最多翻轉 1 個額外的 0 單元來詢問最大島嶼的大小;使用Size優化而不是rank。
[Python解請進]

-----
Try UnionFind to solve. Since the question asks the size of the largest island by flipping at most 1 extra 0-cell; the Size -optimization is used instead of rank.

  1. class UnionFind:
  2. def __init__(self, N):
  3. self.root = list(range(N))
  4. self.Size = [1]*N
  5.  
  6. def Find(self, x):
  7. if self.root[x] != x:
  8. self.root[x] = self.Find(self.root[x]) # path compression
  9. return self.root[x]
  10.  
  11. def Union(self, x, y):
  12. x = self.Find(x)
  13. y = self.Find(y)
  14. if x==y: return False
  15.  
  16. if self.Size[x] > self.Size[y]:
  17. self.Size[x] += self.Size[y]
  18. self.root[y]=x
  19. else:
  20. self.Size[y] += self.Size[x]
  21. self.root[x]=y
  22. return True
  23.  
  24. class Solution:
  25. def largestIsland(self, grid: List[List[int]]) -> int:
  26. n=len(grid)
  27. N=n*n
  28. d=(0, 1, 0, -1, 0)
  29. def inside(i, j):
  30. return 0<=i<n and 0<=j<n
  31. def idx(i, j):
  32. return i*n+j
  33.  
  34. G=UnionFind(N)
  35. maxSz=1
  36. for i, row in enumerate(grid):
  37. for j, x in enumerate(row):
  38. if x==1:
  39. a=idx(i, j)
  40. D=grid[i+1][j] if i<n-1 else 0
  41. R=grid[i][j+1] if j<n-1 else 0
  42. if D>0:
  43. b=a+n
  44. if G.Union(a, b):
  45. maxSz=max(maxSz, G.Size[G.Find(a)])
  46. if R>0:
  47. b=a+1
  48. if G.Union(a, b):
  49. maxSz=max(maxSz, G.Size[G.Find(a)])
  50. for i, row in enumerate(grid):
  51. for j, x in enumerate(row):
  52. if x==0:
  53. component=set()
  54. for a in range(4):
  55. r, s=i+d[a], j+d[a+1]
  56. if inside(r, s) and grid[r][s]==1:
  57. component.add(G.Find(idx(r, s)))
  58. if len(component)==0: continue
  59. sz=1+sum(G.Size[c] for c in component)
  60. maxSz=max(maxSz, sz)
  61. return maxSz

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章