1. Empty contributes 0
Out-of-bounds or water adds no area.
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
return 0;
}Typorithm · medium
Step 1 of 8 · intro card
Graphs
Flood-fill each island while summing its cells, and keep the maximum area across all islands.
Like counting islands, but each flood fill returns the island's area instead of just marking it.
Area is one for the current cell plus the areas returned from its four neighbors.
The outer scan keeps the largest area produced by any starting cell.
Return 1 + four neighbor areas.
Sink cells to count once.
Track the running maximum.
function maxAreaOfIsland(grid) {
const rows = grid.length;
const cols = grid[0].length;
let best = 0;
function area(r, c) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
return 0;
}
grid[r][c] = 0;
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1);
}
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (grid[r][c] === 1) {
best = Math.max(best, area(r, c));
}
}
}
return best;
}Connect each part of the code to the concept before you type.
Out-of-bounds or water adds no area.
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
return 0;
}Sink the cell so it is counted once.
grid[r][c] = 0This cell plus the four neighbor areas is the island size.
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)Keep the largest island area found.
best = Math.max(best, area(r, c))Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.