QuestionsDSA

Number of Islands

DFS (Depth-First)MediumDSA

Given a grid of '1' (land) and '0' (water), count the islands (land connected 4-directionally).

What it tests

Grid-as-graph, and 'flood fill' to mark a whole component visited.

Approach & answer

Scan the grid; each time you hit unvisited land, that's a new island — then DFS/flood-fill to sink the entire connected landmass so you don't recount it. Treat the grid as a graph where neighbors are up/down/left/right. Mutating visited land to '0' in place is the cheap way to mark visited (mention it destroys the input; use a separate visited set if the grid must survive). Recursive DFS can stack-overflow on a huge all-land grid — an explicit stack or BFS queue is the safe alternative. Same skeleton (find a seed, flood its component, count) solves max-area-of-island and surrounded-regions.

Use this technique when

Connected regions / components in a grid or graph → DFS or BFS flood fill, marking visited.

Complexity

Time O(rows·cols) · Space O(rows·cols) worst-case recursion

References

js