Graph Theory37 sections · 1633 units
Open in Course

LeetCode 695 Max Area of Island - Algorithm

Recursive area calculation

Your DFS function now returns an integer instead of void. Here's the approach:

1.1. Loop through every cell. When you find an unvisited land cell, call DFS on it.

2.2. In DFS, if the cell is out of bounds or water, return 00.

3.3. Mark the current cell as visited by setting it to 00.

4.4. Return 11 (current cell) plus the DFS results from all 44 neighbors.

5.5. In the main loop, compare each DFS result to your running maximum.

The recursion builds area bottom-up. Leaf cells return 11. Parent calls sum these up, giving you the total island size.