medium +20 pts

Max Area of Island

Find the largest connected region of 1s in a binary grid.

You are given a 2D list `grid` of integers, where each cell is either `0` (water) or `1` (land). An island is a group of connected `1`s. Two cells are connected if they are adjacent horizontally or vertically (not diagonally). The area of an island is the number of `1`s it contains. Write a function `max_area_of_island(grid)` that returns the maximum island area. If there are no islands, return `0`. The grid may be empty or have zero rows/columns.

Constraints

0 <= len(grid) <= 100; 0 <= len(grid[0]) <= 100. The grid is a list of lists of integers, each element is 0 or 1. The function should not modify the input grid. Time complexity should be O(R*C) where R and C are grid dimensions.

Example

['>>> max_area_of_island([[0,0,1,0,0],\n...                   [1,1,1,0,0],\n...                   [0,1,0,0,0],\n...                   [1,1,0,0,0]])\n5', '>>> max_area_of_island([[0,0,0],\n...                   [0,0,0])\n0', '>>> max_area_of_island([[]])\n0']
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about how to traverse all cells that belong to the same island exactly once.
A depth-first search (DFS) can be used to explore an island's area. Mark visited cells to avoid recounting.
Try using recursion or an explicit stack; either works.
Edge case: empty grid or all water should yield 0.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.