Max Area of Island

Medium

Topics
GraphDFSBFSMatrix

Given an m x n binary grid, return the area (number of cells) of the largest island. Cells connect horizontally or vertically. If there is no island, return 0.

Example 1

0001011110201000123
largest island
Islands are groups of 1s joined horizontally or vertically. The answer is the cell count of the biggest one — 5 here — not the number of islands.
2D grid — one row per line.
Input:  grid = [[0,0,1,0],[1,1,1,0],[0,1,0,0]]
Output: 5

Example 2

00001000012
Input:  grid = [[0,0,0],[0,0,0]]
Output: 0

Constraints

  • 1 <= m, n <= 50
  • grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Same flood-fill as counting islands, except instead of counting components you sum the cells in each component and track the maximum.

Approach

  1. For each unvisited land cell, DFS returns the size of its component.
  2. DFS sinks the cell (set to 0) and adds 1 plus the sizes of its four neighbours.
  3. Keep the maximum size seen.

Dry Run

grid  0 0 1 0
      1 1 1 0
      0 1 0 0
  start (0,2)  sinks (0,2) (1,2) (1,1) (1,0) (2,1)   area 5
  every other start finds water or an already-sunk cell, returning 0
answer 5
The recursion returns an AREA rather than filling a counter: `1 + ` the four
neighbours, so each frame contributes itself and trusts its children for the rest.
No accumulator is passed down and nothing is shared between branches.
`grid[r][c] = 0` must come BEFORE the four recursive calls. Sink after them and the
walk steps straight back into the cell it came from, recursing between two
neighbours until it dies with RecursionError: maximum recursion depth exceeded --
which is what this grid does.
Sinking as you go means the grid doubles as the visited set, so the outer double
loop can call dfs on every cell without checking anything: a cell already consumed
by an earlier island returns 0 immediately. That also mutates the input, which is
fine when the caller does not need it again and worth stating when they might.
One frame per cell is the cost. At the stated 300 x 300 limit an all-land grid is
90000 frames deep -- this page raises Python's recursion limit so the tests can
run, and with the default 1000 the crossover is between a 30 x 30 grid, which
passes, and 32 x 32, which does not.

Complexity

  • Time — O(m*n): each cell is visited once.
  • Space — O(m*n): recursion depth.

Common Pitfalls

  • Sink the cell before recursing. Without grid[r][c] = 0 the walk steps back into the cell it came from and recurses until it dies with RecursionError: maximum recursion depth exceeded.
  • This mutates the input grid. That is fine when the caller does not need it again and worth stating when they might -- a separate visited set is the alternative, at O(RC) extra space.
  • The recursive flood fill costs one stack frame per cell, so a single component of k cells is k frames deep. At the stated limit of 300 x 300 that is 90000 frames for an all-land grid. This page raises Python's recursion limit so the tests can run; with the default limit of 1000, a 32 x 32 all-land grid already raises RecursionError while 30 x 30 still passes. Say so, and offer the explicit-stack version that sinks on push.

Full Solution — all languages

class Solution:
    def maxAreaOfIsland(self, grid):
        R,C=len(grid),len(grid[0])
        def dfs(r,c):
            if r<0 or r>=R or c<0 or c>=C or grid[r][c]==0: return 0
            grid[r][c]=0
            return 1+dfs(r+1,c)+dfs(r-1,c)+dfs(r,c+1)+dfs(r,c-1)
        best=0
        for r in range(R):
            for c in range(C):
                best=max(best,dfs(r,c))
        return best
SensAI
Beta
Tap the mic to stop voice mode