SDE & MLE Prep

695. Max Area of Island

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))