Intuition
Scan for land cells; from each unvisited one, flood-fill its whole island counting cells, sinking each cell as you visit it so it isn't counted twice.
Explanation
Walk-through
- Scan every cell. When you hit a
1, launch a DFS that returns the area of the island it belongs to. - The DFS sinks each visited land cell to
0(marking it visited) and returns1 + area of the four neighbours. - Track the maximum island area across all launches.
dfs(r, c):
if out of bounds or grid[r][c] == 0: return 0
grid[r][c] = 0 # sink so we never recount
return 1 + dfs(r+1,c)+dfs(r-1,c)+dfs(r,c+1)+dfs(r,c-1)
Worked example
[[1,1,0,0],[1,0,0,1],[0,0,1,1]]:
- Island A: (0,0),(0,1),(1,0) → area 3.
- Island B: (1,3),(2,3),(2,2) → area 3.
- Max = 3.
Complexity
- Time: O(m·n) — each cell visited once.
- Space: O(m·n) recursion in the worst case (one giant island).
Implementation
class Solution {
private int rows, cols;
public int maxAreaOfIsland(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) return 0;
rows = grid.length;
cols = grid[0].length;
int best = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 1) {
best = Math.max(best, dfs(grid, r, c));
}
}
}
return best;
}
private int dfs(int[][] grid, int r, int c) {
if (r < 0 || r >= rows || c < 0 || c >= cols || 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);
}
}