Making A Large Island (LeetCode 827): Solution and Explanation
Given an n x n grid of land (1) and water (0), you may turn at most one water cell into land. Return the area of the largest island you can end up with.
Intuition
Flipping one water cell can only glue together the islands that touch it. The new island is that cell plus every island sitting directly above, below, left or right of it.
Recomputing island areas after each possible flip would cost O(n^2) per flip. Instead, label every island once with its own id and remember its area. Then any water cell can be scored instantly from its four neighbours.
The one trap is counting the same island twice. If an island wraps around a water cell, two neighbours carry the same id, so collect distinct ids before adding areas.
Approach: Island ids plus a bridge test per water cell
- Scan the grid. At each unlabelled land cell, flood fill its island with a new id (starting at 2, so ids never clash with 0 and 1) and store
size[id]. - Set
bestto the largest area, which is the answer when there is no water to flip. - For each water cell, gather the distinct ids among its four neighbours.
- Its score is 1 plus the sum of those areas. Keep the maximum in
bestand return it.
Step-by-step example
grid = [[1,0],[0,1]]
- The cell (0,0) starts island 2 with area 1. The cell (1,1) starts island 3 with area 1.
- Without flipping, best = 1.
- Flip (0,1): its neighbours (0,0) and (1,1) belong to islands 2 and 3, so the score is 1 + 1 + 1 = 3. best = 3.
- Flip (1,0): the same two islands touch it, so the score is again 3.
- Return 3.
Code: Python, Java, C++
1class Solution:
2 def largestIsland(self, grid: List[List[int]]) -> int:
3 n = len(grid)
4 size = {}
5 label = 2
6 for r in range(n):
7 for c in range(n):
8 if grid[r][c] == 1:
9 stack = [(r, c)]
10 grid[r][c] = label
11 area = 0
12 while stack:
13 x, y = stack.pop()
14 area += 1
15 for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
16 if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 1:
17 grid[nx][ny] = label
18 stack.append((nx, ny))
19 size[label] = area
20 label += 1
21 best = max(size.values(), default=0)
22 for r in range(n):
23 for c in range(n):
24 if grid[r][c] == 0:
25 seen = set()
26 for nx, ny in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
27 if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] > 1:
28 seen.add(grid[nx][ny])
29 best = max(best, 1 + sum(size[i] for i in seen))
30 return best1class Solution {
2 public int largestIsland(int[][] grid) {
3 int n = grid.length;
4 Map<Integer, Integer> size = new HashMap<>();
5 int label = 2;
6 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
7 for (int r = 0; r < n; r++) {
8 for (int c = 0; c < n; c++) {
9 if (grid[r][c] == 1) {
10 Deque<int[]> stack = new ArrayDeque<>();
11 stack.push(new int[]{r, c});
12 grid[r][c] = label;
13 int area = 0;
14 while (!stack.isEmpty()) {
15 int[] cell = stack.pop();
16 area++;
17 for (int[] d : dirs) {
18 int nx = cell[0] + d[0], ny = cell[1] + d[1];
19 if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] == 1) {
20 grid[nx][ny] = label;
21 stack.push(new int[]{nx, ny});
22 }
23 }
24 }
25 size.put(label, area);
26 label++;
27 }
28 }
29 }
30 int best = 0;
31 for (int s : size.values()) best = Math.max(best, s);
32 for (int r = 0; r < n; r++) {
33 for (int c = 0; c < n; c++) {
34 if (grid[r][c] == 0) {
35 Set<Integer> seen = new HashSet<>();
36 for (int[] d : dirs) {
37 int nx = r + d[0], ny = c + d[1];
38 if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] > 1) {
39 seen.add(grid[nx][ny]);
40 }
41 }
42 int total = 1;
43 for (int id : seen) total += size.get(id);
44 best = Math.max(best, total);
45 }
46 }
47 }
48 return best;
49 }
50}1class Solution {
2public:
3 int largestIsland(vector<vector<int>>& grid) {
4 int n = grid.size();
5 unordered_map<int, int> size;
6 int label = 2;
7 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
8 for (int r = 0; r < n; r++) {
9 for (int c = 0; c < n; c++) {
10 if (grid[r][c] == 1) {
11 vector<pair<int, int>> st = {{r, c}};
12 grid[r][c] = label;
13 int area = 0;
14 while (!st.empty()) {
15 int x = st.back().first, y = st.back().second;
16 st.pop_back();
17 area++;
18 for (auto& d : dirs) {
19 int nx = x + d[0], ny = y + d[1];
20 if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] == 1) {
21 grid[nx][ny] = label;
22 st.push_back({nx, ny});
23 }
24 }
25 }
26 size[label] = area;
27 label++;
28 }
29 }
30 }
31 int best = 0;
32 for (auto& kv : size) best = max(best, kv.second);
33 for (int r = 0; r < n; r++) {
34 for (int c = 0; c < n; c++) {
35 if (grid[r][c] == 0) {
36 unordered_set<int> seen;
37 for (auto& d : dirs) {
38 int nx = r + d[0], ny = c + d[1];
39 if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] > 1) {
40 seen.insert(grid[nx][ny]);
41 }
42 }
43 int total = 1;
44 for (int id : seen) total += size[id];
45 best = max(best, total);
46 }
47 }
48 }
49 return best;
50 }
51};Time and space complexity
O(n^2)
Each land cell is painted exactly once, and each water cell looks at 4 neighbours.
O(n^2)
The flood fill stack and the id-to-area map can grow to the number of cells.
Other approaches
Union-Find (time O(n^2 α(n)), space O(n^2))
Union every pair of adjacent land cells and keep component sizes at the roots. Then score each water cell from the distinct roots of its neighbours. Same complexity, a little more code.
Brute force flip and recount (time O(n^4), space O(n^2))
Try every water cell, flip it, and run a full flood fill to find the largest island. Simple, but O(n^4), far too slow for n = 500.
Common mistakes
- Adding the same island twice when it touches the water cell from two sides. Deduplicate neighbour ids with a set.
- Returning 0 for a grid that is all land. With no water to flip, the answer is n * n, so initialise best with the largest island.
- Labelling islands with id 1, which cannot be told apart from unvisited land. Start ids at 2.
- Recursive DFS on a 500 x 500 island can overflow the call stack in some languages. An explicit stack avoids it.
Frequently asked questions
Why start island ids at 2?
The grid already uses 0 for water and 1 for unvisited land. Writing ids 2, 3, ... into the grid marks cells as visited and records which island they belong to at the same time.
Do I have to flip a cell?
No, the flip is optional. That is why best starts at the largest existing island, which matters when the grid has no water.
Can a flipped cell join more than two islands?
Yes, up to four, one from each side. The score simply adds every distinct neighbouring island's area plus 1.