|
| 1 | +//https://leetcode.com/problems/making-a-large-island/ |
| 2 | + |
| 3 | +package making_a_large_island |
| 4 | + |
| 5 | +func largestIsland(grid [][]int) int { |
| 6 | + n := len(grid) |
| 7 | + ds := NewDisjointSet(n * n) |
| 8 | + for i := 0; i < n; i++ { |
| 9 | + for j := 0; j < n; j++ { |
| 10 | + if grid[i][j] == 1 { |
| 11 | + if i > 0 && grid[i-1][j] == 1 { |
| 12 | + ds.Union(i*n+j, (i-1)*n+j) |
| 13 | + } |
| 14 | + if j > 0 && grid[i][j-1] == 1 { |
| 15 | + ds.Union(i*n+j, i*n+j-1) |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + groupSize := make(map[int]int) |
| 21 | + for i := 0; i < n; i++ { |
| 22 | + for j := 0; j < n; j++ { |
| 23 | + if grid[i][j] == 1 { |
| 24 | + groupSize[ds.Find(i*n+j)]++ |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + maxSize := 0 |
| 29 | + for _, v := range groupSize { |
| 30 | + maxSize = max(maxSize, v) |
| 31 | + } |
| 32 | + for i := 0; i < n; i++ { |
| 33 | + for j := 0; j < n; j++ { |
| 34 | + if grid[i][j] == 0 { |
| 35 | + seen := make(map[int]bool) |
| 36 | + size := 1 |
| 37 | + if i > 0 && grid[i-1][j] == 1 { |
| 38 | + seen[ds.Find((i-1)*n+j)] = true |
| 39 | + } |
| 40 | + if j > 0 && grid[i][j-1] == 1 { |
| 41 | + seen[ds.Find(i*n+j-1)] = true |
| 42 | + } |
| 43 | + if i < n-1 && grid[i+1][j] == 1 { |
| 44 | + seen[ds.Find((i+1)*n+j)] = true |
| 45 | + } |
| 46 | + if j < n-1 && grid[i][j+1] == 1 { |
| 47 | + seen[ds.Find(i*n+j+1)] = true |
| 48 | + } |
| 49 | + for k := range seen { |
| 50 | + size += groupSize[k] |
| 51 | + } |
| 52 | + maxSize = max(maxSize, size) |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return maxSize |
| 57 | +} |
| 58 | + |
| 59 | +func max(a int, b int) int { |
| 60 | + if a > b { |
| 61 | + return a |
| 62 | + } |
| 63 | + return b |
| 64 | +} |
| 65 | + |
| 66 | +type DisjointSet struct { |
| 67 | + parent []int |
| 68 | + groupSize []int |
| 69 | +} |
| 70 | + |
| 71 | +func NewDisjointSet(n int) *DisjointSet { |
| 72 | + parent := make([]int, n) |
| 73 | + groupSize := make([]int, n) |
| 74 | + for i := 0; i < n; i++ { |
| 75 | + parent[i] = i |
| 76 | + groupSize[i] = 1 |
| 77 | + } |
| 78 | + return &DisjointSet{parent, groupSize} |
| 79 | +} |
| 80 | + |
| 81 | +func (ds *DisjointSet) Find(x int) int { |
| 82 | + if ds.parent[x] != x { |
| 83 | + ds.parent[x] = ds.Find(ds.parent[x]) |
| 84 | + } |
| 85 | + return ds.parent[x] |
| 86 | +} |
| 87 | + |
| 88 | +func (ds *DisjointSet) Union(x, y int) { |
| 89 | + xRoot := ds.Find(x) |
| 90 | + yRoot := ds.Find(y) |
| 91 | + if xRoot == yRoot { |
| 92 | + return |
| 93 | + } |
| 94 | + if ds.groupSize[xRoot] < ds.groupSize[yRoot] { |
| 95 | + ds.parent[xRoot] = yRoot |
| 96 | + ds.groupSize[yRoot] += ds.groupSize[xRoot] |
| 97 | + } else { |
| 98 | + ds.parent[yRoot] = xRoot |
| 99 | + ds.groupSize[xRoot] += ds.groupSize[yRoot] |
| 100 | + } |
| 101 | +} |
0 commit comments