CodingNodes / Graphs / Max Area of Island System design Space play · ←→ step · R restart

Problem

A map is a grid of 0 (water) and 1 (land).

An island is a group of land cells connected up, down, left or right; diagonal touching does not connect them. The area of an island is its number of cells.

Return the area of the largest island, or 0 if there is no land. You may change the grid while you work.

Constraints

  • 1 ≤ rows, cols ≤ 50
  • grid[r][c] is 0 or 1

Examples: pick one to animate

Solutions

TimeO(rows · cols) SpaceO(rows · cols)

Time: The scan visits each cell once. Each land cell is sunk, pushed and popped once, and each pop checks 4 neighbors.

Space: In the worst case (all land) the stack can hold O(rows · cols) cells. An explicit stack avoids deep recursion on a snake-shaped island.

Scan for land. For each unsunk land cell, flood its island with a stack: pop a cell, add 1 to area, and push every land neighbor after sinking it (set it to 0). When the stack empties, compare the area with best.