sagelearnai

Max Area of Island

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #695

In a binary grid (1 = land, 0 = water), an island's area is its number of 4-directionally connected land cells. Return the largest island's area, or 0 if there is no land.

Example

text
grid = [[1, 1, 0, 0],
        [0, 1, 0, 1],
        [0, 0, 1, 1],
        [0, 0, 1, 0]]   →  4    (bottom-right island)

Hints

  1. Same flood fill as Number of Islands, but count cells as you visit them.

Approach

For each unvisited land cell, flood-fill its island while counting cells (mark visited by setting the cell to 0). Track the maximum count. O(R·C).

Complexity

Time: O(R·C). Space: O(R·C).

Python solution
def maxAreaOfIsland(grid):
    R, C = len(grid), len(grid[0])
    best = 0
    for r in range(R):
        for c in range(C):
            if grid[r][c] != 1:
                continue
            grid[r][c] = 0
            stack, area = [(r, c)], 0
            while stack:
                x, y = stack.pop()
                area += 1
                for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
                    if 0 <= nx < R and 0 <= ny < C and grid[nx][ny] == 1:
                        grid[nx][ny] = 0
                        stack.append((nx, ny))
            best = max(best, area)
    return best
JavaScript solution
function maxAreaOfIsland(grid) {
  const R = grid.length, C = grid[0].length;
  let best = 0;
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
    if (grid[r][c] !== 1) continue;
    grid[r][c] = 0;
    const stack = [[r, c]]; let area = 0;
    while (stack.length) {
      const [x, y] = stack.pop(); area++;
      for (const [nx, ny] of [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]) {
        if (nx >= 0 && ny >= 0 && nx < R && ny < C && grid[nx][ny] === 1) { grid[nx][ny] = 0; stack.push([nx, ny]); }
      }
    }
    best = Math.max(best, area);
  }
  return best;
}