AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Max Area of Island

The key idea

Every 1 belongs to exactly one island. Flood-fill from each unvisited land cell, counting how many 1s the flood reaches, and sink each visited cell to 0 so it is never counted twice. The largest flood count is the answer.

Problem

You are given an m x n binary matrix grid. An island is a group of 1s (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Constraints

Examples

Input: grid = [[0,0,1,0,0],[0,1,1,0,0],[0,0,0,1,1]] Output: 3
Input: grid = [[0,0,0,0],[0,0,0,0]] Output: 0

Complexity

Time: O(m*n) Space: O(m*n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems