This is like number of islands except we also have to count the size of each island, which is done like so.
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
max_area = 0
visited = set()
m, n = len(grid), len(grid[0])
def inbounds(y, x):
return 0 <= y < m and 0 <= x < n
def visit(y, x):
if (y, x) in visited:
return 0
if not inbounds(y, x):
return 0
if grid[y][x] != 1:
return 0
visited.add((y, x))
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
return 1 + sum([visit(dy + y, dx + x) for dy, dx in dirs])
for y in range(m):
for x in range(n):
if grid[y][x] == 1:
max_area = max(max_area, visit(y, x))
return max_area