Count distinct islands in a 2D grid using DFS traversal
The grid is an implicit graph with m×n vertices and ≤ 4×m×n edges (4-connectivity). DFS on a graph is O(V + E). Since E = O(V) in a grid, total time is O(m × n). Each cell is processed exactly once: either by the main loop (water) or by DFS (land, then marked).
Counting connected components via DFS/BFS is a standard graph traversal pattern—the key is ensuring each vertex is visited exactly once.
The worst-case recursion depth occurs when the entire grid forms a single snake-like island (e.g., a spiral). In this case, DFS may recurse through all m×n cells before returning. BFS limits queue size to the current frontier, which is O(min(m,n)) for a connected component.
Iterative DFS with explicit stack or BFS can avoid stack overflow for large grids, trading recursion elegance for robustness.