Max Area of Island
Medium
Topics
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
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
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
- For each unvisited land cell, DFS returns the size of its component.
- DFS sinks the cell (set to 0) and adds 1 plus the sizes of its four neighbours.
- 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] = 0the walk steps back into the cell it came from and recurses until it dies withRecursionError: 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
RecursionErrorwhile 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 bestimport java.util.*;
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int R=grid.length,C=grid[0].length,best=0;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)best=Math.max(best,dfs(grid,r,c));
return best;
}
int dfs(int[][] grid,int r,int c) {
int R=grid.length,C=grid[0].length;
if(r<0||r>=R||c<0||c>=C||grid[r][c]==0)return 0;
grid[r][c]=0;
return 1+dfs(grid,r+1,c)+dfs(grid,r-1,c)+dfs(grid,r,c+1)+dfs(grid,r,c-1);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxAreaOfIsland(vector<vector<int>>& grid) {
int R=grid.size(),C=grid[0].size(),best=0;
function<int(int,int)> dfs=[&](int r,int c) {
if(r<0||r>=R||c<0||c>=C||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);
};
for(int r=0;r<R;r++)for(int c=0;c<C;c++)best=max(best,dfs(r,c));
return best;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maxAreaOfIsland = function(grid) {
const R=grid.length,C=grid[0].length;
function dfs(r,c) {
if(r<0||r>=R||c<0||c>=C||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);
}
let best=0;
for(let r=0;r<R;r++)for(let c=0;c<C;c++)best=Math.max(best,dfs(r,c));
return best;
};