Medium · Grid DFS
Understand → Visualise → Practice.
A grid is a graph in disguise: each cell is a node connected to the cells above, below, left and right of it.
Scan every cell. When you find unvisited land, count a new island and flood-fill everything connected to it.
Row by row, column by column.
New land → island count + 1.
DFS or BFS through the 4 neighbours.
O(rows × cols) time and space in the worst case.
Mark cells when you push them, not when you pop them, or the same cell can be queued many times.
Read the full guides first: Binary Trees and Traversals, Binary Search Trees, Graphs, BFS and DFS, Weighted Graphs, Dijkstra and Union–Find.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.