Graph Theory37 sections · 1633 units
Open in Course

LeetCode 695 Max Area of Island - Core Idea

DFS returns size

Here is the step-by-step approach:

1.1. Loop through every cell in the grid.

2.2. If you find a land cell (11) that has not been visited, trigger DFS from that cell.

3.3. DFS marks the cell as visited (set to 00), then recursively calls DFS on all 44 neighbors. Each recursive call returns the area of that branch.

4.4. DFS returns 11 (current cell) plus the sum of areas from all neighbors.

5.5. Track the maximum area returned by any DFS call.

6.6. Return the maximum after visiting all cells.

The recursion builds the area bottom-up, starting from leaf cells and accumulating as it returns.