Graph Theory37 sections · 1633 units
Open in Course

LeetCode 200 Number of Islands - Core Idea

Find and Erase

How do you count them without counting the same island twice? you use a loop and a traversal.

1.1. Loop through every cell in the grid.

2.2. If you find a cell that is '11' (Land): - you increment your island_count. - you immediately trigger a traversal (DFS or BFS) from that cell. - As you traverse the island, you mark every cell you visit as '00' (Water) or '22' (Visited).

3.3. By erasing the island as you visit it, your main loop will never accidentally count it again.