Skip to problem
←

Making a Large Island

Hard 0 attempts

You're given an n x n binary grid, and you're allowed to flip at most one 0 into a 1. After doing so (or choosing not to), return the size of the biggest island you can produce. An island here means a group of 1s connected up, down, left, or right — diagonal neighbors don't count.

Area means the number of cells in one connected island, not the total number of 1s in the grid. A flip may join several islands, but each original island is counted only once. An all-water grid returns 1; an all-land grid returns n × n.

Function contract

Implement largestIsland(grid). Receive a nonempty n × n matrix containing only numeric 0 and 1. You may modify the matrix while computing the answer.

Output: Return the largest possible island area (number of cells) after changing at most one 0 to 1.

Example 1

Input
grid = [[1,0],[0,1]]
Output
3

Example 2

Input
grid = [[1,1],[1,1]]
Output
4

Example 3

Input
grid = [[0,0],[0,0]]
Output
1
Visual Aid
One flip can merge several islands
One flip joins four islands into an island of area fiveBefore: land occupies the top middle, middle left, middle right, and bottom middle cells of a three by three grid. Flipping the center from zero to one connects all four.010101010Four separate islands010111010One island: area 5→Flip the center: 1 + 1 + 1 + 1 + 1 = 5

Diagonal contact does not connect the original four islands. Changing the center cell connects them through shared edges.

Constraints
  • 1 <= n <= 500
  • grid[i][j] is 0 or 1
Topics

Island Labels and Sizes

Label each island with a distinct ID using an explicit stack. For each zero, add the sizes of its distinct neighboring islands plus one. Counting each ID once avoids double counting an island touching the zero on multiple sides.

javascript
function largestIsland(grid) {
  const n = grid.length,
    dirs = [
      [1, 0],
      [-1, 0],
      [0, 1],
      [0, -1],
    ],
    sizes = new Map();
  let id = 2,
    best = 0;
  for (let r = 0; r < n; r++)
    for (let c = 0; c < n; c++)
      if (grid[r][c] === 1) {
        const stack = [[r, c]];
        grid[r][c] = id;
        let size = 0;
        while (stack.length) {
          const [x, y] = stack.pop();
          size++;
          for (const [dx, dy] of dirs) {
            const nx = x + dx,
              ny = y + dy;
            if (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] === 1) {
              grid[nx][ny] = id;
              stack.push([nx, ny]);
            }
          }
        }
        sizes.set(id++, size);
        best = Math.max(best, size);
      }
  for (let r = 0; r < n; r++)
    for (let c = 0; c < n; c++)
      if (grid[r][c] === 0) {
        const seen = new Set();
        let total = 1;
        for (const [dr, dc] of dirs) {
          const nr = r + dr,
            nc = c + dc;
          if (
            nr >= 0 &&
            nr < n &&
            nc >= 0 &&
            nc < n &&
            grid[nr][nc] > 1 &&
            !seen.has(grid[nr][nc])
          ) {
            seen.add(grid[nr][nc]);
            total += sizes.get(grid[nr][nc]);
          }
        }
        best = Math.max(best, total);
      }
  return best;
}

Time: O(n²) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript