DFS
Depth-first search on a grid: each cell is a vertex with edges to its 4
neighbours, and from any unvisited cell DFS floods as far as it can before
backtracking. See
Grids as Graphs for the neighbour function,
the visited choices, and why the recursive version dies on a large grid.
Connected Components
A maximal set of cells all reachable from each other. The two-loop shape - outer scan finds fresh land, inner traversal sinks the whole island - is flood fill.
200. Number of Islands
Medium·
1
DFS - Recursive
O(m*n)
O(m*n)
FIG. 200 NUMBER OF ISLANDS● INTERACTIVE
visualization loads as you reach it
- Time
- O(m*n)
mandnare the grid's row and column counts. The nested scan visits each of them*ncells once, anddfsvisits each land cell at most once thanks to thevisitedguard.- Space
- O(m*n)
visitedis anm*ngrid. The recursion call stack can also grow tom*nin the worst case (one giant island snaking through every cell).
419. Battleships in a Board
Medium·
1
DFS - Recursive
O(m*n)
O(m*n)
FIG. 419 BATTLESHIPS IN A BOARD● INTERACTIVE
visualization loads as you reach it
- Time
- O(m*n)
- The
for row in range(m): for col in range(n)double loop visits every cell once;dfsmarks eachXcell invisitedexactly once and returns immediately on already-visited or non-Xcells, so total work isO(m*n), wheremis the number of rows andnis the number of columns. - Space
- O(m*n)
visitedis a fullm x ngrid:O(m*n).- The recursion stack adds at most
O(m*n)more in the worst case (a single battleship snaking through every cell), which does not change the overall order.
694. Number of Distinct Islands
Medium·
1
DFS - Recursive
O(m×n)
O(m×n)
FIG. 694 NUMBER OF DISTINCT ISLANDS● INTERACTIVE
visualization loads as you reach it
- Time
- O(m×n)
dfsvisits each of them×ncells at most once, guarded byvisited.- Space
- O(m×n)
visitedis anm×narray, and across all islands the total length of everypathrecorded intoisland_signatureis bounded bym×ncells.
733. Flood Fill
Easy·
733Flood Fill
1
DFS - Recursive
O(m*n)
O(m*n)
FIG. 733 FLOOD FILL● INTERACTIVE
visualization loads as you reach it
- Time
- O(m*n)
mis the number of rows,nis the number of columns -dfsvisits every cell at most once, guarded by thevisitedcheck.- Space
- O(m*n)
visitedallocates one entry per cell,O(m*n).- The
dfsrecursion stack can grow toO(m*n)frames in the worst case, when the whole grid is one connected region.
1034. Coloring A Border
Medium·
1
DFS - Two Phase
O(m×n)
O(m×n)
FIG. 1034 COLORING A BORDER● INTERACTIVE
visualization loads as you reach it
- Time
- O(m×n)
dfsvisits each of the grid'sm × ncells at most once, sincevisited[r][c]gates re-entry.- Space
- O(m×n)
visitedandbordersare each a fullm × nmatrix.- The
dfsrecursion stack can also grow toO(m×n)in the worst case, but stays the same order as the two matrices.
463. Island Perimeter
Easy·
1
DFS - Recursive
O(2mn)
O(2mn)
FIG. 463 ISLAND PERIMETER● INTERACTIVE
visualization loads as you reach it
- Time
- O(2mn)
mis the number of rows,nis the number of columns.- The outer scan (
for row in range(m): for col in range(n)) looking for the first unvisited land cell is oneO(mn)pass in the worst case (the island sits at the far end of row-major order). - The
dfscall visits every land cell exactly once (visited[row][col]guards re-entry), a secondO(mn)pass in the worst case (grid is all land). - Space
- O(2mn)
visitedis anm x nmatrix -O(mn).- The recursive
dfscall stack can go as deep as the number of land cells in a snake-shaped island - anotherO(mn)in the worst case.
695. Max Area of Island
Medium·
1
DFS - Recursive
O(m×n)
O(m×n)
FIG. 695 MAX AREA OF ISLAND● INTERACTIVE
visualization loads as you reach it
- Time
- O(m×n)
mandnare the grid's row and column counts. The outer double loop visits each cell once, anddfsvisits each land cell at most once thanks to thevisitedcheck.- Space
- O(m×n)
visitedis anm×nmatrix.- The recursion stack can also grow to
m×nframes in the worst case (one fully connected island) - the same order asvisited.
3619. Count Islands With Total Value Divisible by K
Medium·
1
DFS - Recursive
O(m * n)
O(m * n)
FIG. 3619 COUNT ISLANDS DIVISIBLE● INTERACTIVE
visualization loads as you reach it
- Time
- O(m * n)
m, n = len(grid), len(grid[0]). Thefor row/for colscan visits every cell once, anddfsonly recurses into a cell if it is unvisited land, so each of them * ncells is processed bydfsexactly once overall.- Space
- O(m * n)
visitedis anmbynmatrix -O(m * n).- The
dfsrecursion call stack can grow to hold every cell of a single island, up tom * nframes in the worst case (one connected island spanning the whole grid).
1254. Number of Closed Islands
Medium·
1
DFS - Recursive
O(m×n)
O(m×n)
FIG. 1254 NUMBER OF CLOSED ISLANDS● INTERACTIVE
visualization loads as you reach it
- Time
- O(m×n)
- The double loop over
row/colvisits each of them × ncells, anddfsmarks each land cellvisitedat most once before returning. - Space
- O(m×n)
visitedis anm × ngrid.- The
dfsrecursion stack can grow toO(m×n)in the worst case (a single island spanning the whole grid).
1905. Count Sub Islands
Medium·
1
DFS - Recursive
O(m * n)
O(2 * m * n)
FIG. 1905 COUNT SUB ISLANDS● INTERACTIVE
visualization loads as you reach it
- Time
- O(m * n)
- The outer
for row/for colloop scans allm * ncells;dfsvisits any given cell at most once thanks to thevisitedguard, so total work across alldfscalls is bounded bym * n. - Space
- O(2 * m * n)
visitedis anmbyngrid,O(m * n).dfsrecurses into all 4 directions, so on a snake-shaped island the call stack can hold up tom * nframes - anotherO(m * n)term of the same order.
827. Making A Large Island
Hard·
1
DFS + Island Labeling
O(2mn)
O(mn)
FIG. 827 MAKING A LARGE ISLAND● INTERACTIVE
visualization loads as you reach it
- Time
- O(2mn)
- The first nested loop scans all
m×ncells;dfslabels every land cell exactly once (guarded byvisited) -mn. - The second nested loop scans all
m×ncells again, checking at most 4 neighbors per water cell inO(1)-mn. - Two full grid passes, each
O(mn)-2mn. - Space
- O(mn)
visitedis anm×ngrid.island_sizeholds at most one entry per island, bounded bymn.- The
dfsrecursion stack can go as deep as the largest island, up tomnin the worst case (one giant island).
Surrounded Regions
Regions defined by what they cannot reach. Detecting "enclosed" directly is awkward; flooding inward from the border to mark what escapes, then flipping the rest, is one traversal - the border-seeded inversion.
130. Surrounded Regions
Medium·
1
DFS - Recursive
O(2mn)
O(mn)
FIG. 130 SURROUNDED REGIONS● INTERACTIVE
visualization loads as you reach it
- Time
- O(2mn)
mandnare the board's rows and columns. The border-triggereddfscalls mark each reachable'O'cell as'B'at most once, so the flood is bounded byO(mn). The final double loop over every cell is anotherO(mn)pass - two same-order passes collapse to2mn.- Space
- O(mn)
- In the worst case (a snake-shaped safe region), the recursion depth of
dfsgrows to the total number of cells,mn.
417. Pacific Atlantic Water Flow
Medium·
1
DFS - Recursive
O(3·m×n)
O(4·m×n)
FIG. 417 PACIFIC ATLANTIC WATER FLOW● INTERACTIVE
visualization loads as you reach it
- Time
- O(3·m×n)
- The
pacificDFS is started from every cell on the top row and left column (m + nstarts), but thevisited[row][col]guard means no cell is ever explored twice across all of those starts - total work for the whole pacific pass isO(m×n). - The
atlanticDFS is symmetric (started from the bottom row and right column) and is also bounded toO(m×n)total work for the same reason. - The final double loop over
row/colto collect cells reachable from both oceans is one moreO(m×n)pass -m×n + m×n + m×n. - Space
- O(4·m×n)
pacificandatlanticare eachm×nmatrices - two terms ofm×n.- The
dfsrecursion can, in the worst case (e.g. strictly increasing heights), chain through every cell before backtracking, so the call stack depth is up toO(m×n). resultscan hold up to every cell in the grid, anotherO(m×n)-m×n + m×n + m×n + m×n.
1020. Number of Enclaves
Medium·
1
DFS - Recursive
O(m×n)
O(m×n)
FIG. 1020 NUMBER OF ENCLAVES● INTERACTIVE
visualization loads as you reach it
- Time
- O(m×n)
dfsvisits and marks each of them×ncells at most once.- Space
- O(m×n)
visitedis anm×narray; the recursion stack can grow toO(m×n)in the worst case (e.g. one long snaking path of land).