Coding Prep
Max Area of Island
Grid DFS accumulating area: DFS from each unvisited 1-cell, mark visited by setting to 0, return the count of cells reached - track the maximum across all islands.
Problem
Satellite imagery pipelines segment land masses from water to compute coverage metrics. Each cell in a binary grid is either land (1) or water (0), and an island is a group of 1s connected horizontally or vertically. Find the maximum area (number of land cells) of any single island. Return 0 if the grid contains no land.
Grid:
0 0 1 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 1 1
0 1 1 0 1 0 0 0 0 0
0 1 0 0 1 1 0 0 1 0
0 1 0 0 1 1 0 0 1 0
0 0 0 0 0 0 0 0 0 0
→ 5
Grid: [[0,0,0],[0,0,0]] → 0Solution
Approach: Grid DFS that returns an area count, mutating visited cells to sink them.
The outer double loop scans every cell. When it hits a 1, it launches a DFS that floods the entire connected island and returns how many land cells it touched; max_area keeps the running best across those launches. The DFS itself is the key piece. Each call first rejects anything out of bounds or any cell that is not 1 by returning 0 - that single guard handles grid edges, water, and already-visited land in one shot. For a valid land cell it immediately sets grid[row][col] = 0, which is the visited marker: once sunk, no later recursive call can re-enter it, because the very next time the cell is reached it fails the != 1 check. The call then sums 1 for itself plus the four recursive neighbor calls and returns that total, so the count flows back up the call stack and the launching call receives the whole island's size.
Returning an int instead of marking-and-counting-launches is what separates this from Number of Islands. Trace a 2x2 block of 1s: the first DFS sinks the top-left, recurses down and right, each of those sinks itself and finds its remaining neighbor already 0, so the totals fold back to 1 + 1 + 1 + 1 = 4.
Edge cases: All-water grids never launch a DFS, so max_area stays 0; a single isolated 1 returns 1 with no valid neighbors. Marking before recursing prevents a neighbor from re-entering the same cell and double-counting.
Complexity: O(rows * cols) time, O(rows * cols) space - each cell is visited once, and the call stack can grow to the full grid for one snaking island.
Done reading? Mark it so it sticks in your dashboard.