Making A Large Island
Pattern: Disjoint set union
Label every island with its own number and record its size. Then for each water cell, add 1 to the sizes of the different islands around it; the best such total (or the largest island, if there is no water) is the answer.
The problem
Given an n × n grid of 1 (land) and 0 (water), you may change at most one 0 into a 1. Return the size of the largest
island possible.
Think first
- What happens to the islands next to the cell you change?
- How do you avoid adding the same island twice?
- What if the grid is all land?
Hints
Brute force, and why it fails
Try every water cell and re-measure: O(n⁴).
The key insight
Island sizes computed once let each water cell be scored in O(1).
Dry run
| sizes | 2:1 3:1 |
|---|
grid [[1, 0], [0, 1]]. Two islands of size 1, labelled 2 and 3.
Step 1 of 3
The plan
label each island with paint and record its area
for each 0: size = 1 + sum of areas of the distinct neighbouring labels
best = max(largest island, all sizes)
Complexity
- Time
O(n²)- Space
O(n²)
Two passes over the grid.
Edge cases
- All land: n².
- All water: 1.
- One water cell touching the same island from two sides.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int largestIsland(int[][] grid) {
int n = grid.length, label = 2;
Map<Integer, Integer> area = new HashMap<>(); // island label -> its size
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
if (grid[r][c] == 1) area.put(label, paint(grid, r, c, label++)); // give each island its own label
int best = area.isEmpty() ? 0 : Collections.max(area.values());
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
if (grid[r][c] != 0) continue; // try turning this water cell into land
Set<Integer> touched = new HashSet<>();
for (int[] d : dirs) {
int x = r + d[0], y = c + d[1];
if (x >= 0 && y >= 0 && x < n && y < n && grid[x][y] > 1) touched.add(grid[x][y]);
}
int size = 1;
for (int t : touched) size += area.get(t); // each neighbouring island counted once
best = Math.max(best, size);
}
return best;
}
private int paint(int[][] g, int r, int c, int label) {
if (r < 0 || c < 0 || r >= g.length || c >= g.length || g[r][c] != 1) return 0;
g[r][c] = label;
return 1 + paint(g, r + 1, c, label) + paint(g, r - 1, c, label) + paint(g, r, c + 1, label) + paint(g, r, c - 1, label);
}
}C++
class Solution {
public:
int largestIsland(vector<vector<int>>& grid) {
int n = static_cast<int>(grid.size()), label = 2;
unordered_map<int, int> area; // island label -> its size
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
if (grid[r][c] == 1) { area[label] = paint(grid, r, c, label); label++; } // each island its own label
int best = 0;
for (auto& a : area) best = max(best, a.second);
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
if (grid[r][c] != 0) continue; // try turning this water cell into land
set<int> touched;
for (int k = 0; k < 4; k++) {
int x = r + dr[k], y = c + dc[k];
if (x >= 0 && y >= 0 && x < n && y < n && grid[x][y] > 1) touched.insert(grid[x][y]);
}
int size = 1;
for (int t : touched) size += area[t]; // each neighbouring island counted once
best = max(best, size);
}
return best;
}
int paint(vector<vector<int>>& g, int r, int c, int label) {
int n = static_cast<int>(g.size());
if (r < 0 || c < 0 || r >= n || c >= n || g[r][c] != 1) return 0;
g[r][c] = label;
return 1 + paint(g, r + 1, c, label) + paint(g, r - 1, c, label) + paint(g, r, c + 1, label) + paint(g, r, c - 1, label);
}
};Python
class Solution:
def largestIsland(self, grid: list[list[int]]) -> int:
n, label, area = len(grid), 2, {} # island label -> its size
for r in range(n):
for c in range(n):
if grid[r][c] == 1: # give each island its own label
grid[r][c], size, st = label, 0, [(r, c)]
while st:
a, b = st.pop()
size += 1
for x, y in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
if 0 <= x < n and 0 <= y < n and grid[x][y] == 1:
grid[x][y] = label
st.append((x, y))
area[label] = size
label += 1
best = max(area.values(), default=0)
for r in range(n):
for c in range(n):
if grid[r][c] == 0: # try turning this water cell into land
touched = {grid[x][y] for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1))
if 0 <= x < n and 0 <= y < n and grid[x][y] > 1}
best = max(best, 1 + sum(area[t] for t in touched)) # each neighbouring island counted once
return bestCommon mistakes
- Counting one island twice.
- Forgetting the case with no water.