695. Max Area of Island
Asked at 18Meta47Amazon40Google31Bloomberg30Microsoft28Apple22Grubhub100Roku87Intuit73Snowflake67TikTok56Expedia54Zoho52Oracle45DoorDash45Adobe44LinkedIn40Goldman Sachs33
Problem
In a grid of 1s (land) and 0s (water), an island is a group of land cells connected horizontally or vertically, and its area is its cell count. Return the largest island's area, or 0 if there is no land.
Example: [[0,0,1,0,0],[1,1,1,0,0],[0,0,0,1,1],[0,0,0,1,0]] → 4
Same flood fill, but each fill returns the island size; keep the max.
Complexity: O(R·C).
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
R, C = len(grid), len(grid[0])
def area(r, c):
if not (0 <= r < R and 0 <= c < C) or grid[r][c] != 1:
return 0
grid[r][c] = 0
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)
return max(area(r, c) for r in range(R) for c in range(C))
g = [[0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 0]]
assert Solution().maxAreaOfIsland(g) == 4
assert Solution().maxAreaOfIsland([[0, 0, 0, 0, 0]]) == 0
assert Solution().maxAreaOfIsland([[1]]) == 1
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int best = 0;
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++) best = Math.max(best, area(grid, r, c));
return best;
}
private int area(int[][] g, int r, int c) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != 1) return 0;
g[r][c] = 0;
return 1 + area(g, r + 1, c) + area(g, r - 1, c) + area(g, r, c + 1) + area(g, r, c - 1);
}
}
func maxAreaOfIsland(grid [][]int) int {
R, C := len(grid), len(grid[0])
var area func(r, c int) int
area = func(r, c int) int {
if r < 0 || r >= R || c < 0 || c >= C || grid[r][c] != 1 {
return 0
}
grid[r][c] = 0 // visited
return 1 + area(r+1, c) + area(r-1, c) + area(r, c+1) + area(r, c-1)
}
best := 0
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
best = max(best, area(r, c))
}
}
return best
}