Flood Fill / Number of Islands
MediumA grid is a graph where each cell touches its four neighbours. Sink each island as you walk it and count how many walks you start.
gridDFSconnected components
TimeO(rows * cols)
SpaceO(rows * cols) worst case
InputRows of 1 (land) and 0 (water)
Scan the grid. Every unvisited land cell starts a new island.
islands0
1 / 12
for each cell:
if cell is land:
islands++
dfs(cell) // sink the whole island
dfs: mark water, then recurse into 4 neighbours
Why it matters
Overwriting visited land avoids a separate visited matrix.
Keyboard
space play← → stepr restartctrl K search
More in Graphs
Next visualiser
Memoisation vs Brute Force