Max Area of Island
Difficulty: Medium
You're given a grid of 0s (water) and 1s (land). An island is a group of 1s connected horizontally or vertically. Its area is its number of land cells.
Return the largest island's area, or 0 if there's no land.
Examples
Input: grid = [[0,0,1,0,0],[0,0,1,1,1],[0,1,1,0,0],[0,0,0,0,0]]
Output: 6
The 1s at (0,2), (1,2), (1,3), (1,4), (2,1), and (2,2) are all connected into one island of 6 cells - that's the biggest (and only) island here.
Input: grid = [[0,0,0,0]]
Output: 0
There's no land, so the largest island has area 0.
Input: grid = [[1,0],[0,1]]
Output: 1
The two 1s only touch diagonally, not horizontally/vertically, so they're two separate islands, each of area 1.
Constraints
1 <= rows, cols <= 50
grid[i][j] is either 0 or 1
Approach
This builds on counting islands: scan the grid, and from each unvisited land cell, spread to every connected cell. This time, count the cells you visit and compare to the largest area so far.
With DFS, have the function return 1 (for the current cell) plus the counts from its neighbors' calls. With BFS, add one to a counter for each cell popped off the queue.
Solutions
DFS - Recursive Area Count
For each unvisited land cell, explore its island recursively. Each call returns 1 plus the areas from its four neighbors. Track the largest area.
function maxAreaOfIsland(grid) {
const rows = grid.length;
const cols = grid[0].length;
let maxArea = 0;
function dfs(r, c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] !== 1) {
return 0;
}
grid[r][c] = 0; // mark visited
return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1);
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 1) {
maxArea = Math.max(maxArea, dfs(r, c));
}
}
}
return maxArea;
}Time: O(rows × cols) · Space: O(rows × cols)
BFS - Iterative Area Count
For each unvisited land cell, run a queue-based flood fill. The number of cells popped off the queue is the island's area.
function maxAreaOfIsland(grid) {
const rows = grid.length;
const cols = grid[0].length;
let maxArea = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== 1) continue;
let area = 0;
grid[r][c] = 0;
const queue = [[r, c]];
while (queue.length > 0) {
const [row, col] = queue.shift();
area++;
const neighbors = [[row + 1, col], [row - 1, col], [row, col + 1], [row, col - 1]];
for (const [nr, nc] of neighbors) {
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) {
grid[nr][nc] = 0;
queue.push([nr, nc]);
}
}
}
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}Time: O(rows × cols) · Space: O(rows × cols)