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·
2 Approaches · 2 patterns
DFS - Recursive
O(m*n)O(2mn)
DSU: Cell-Index Mapping↗ DSU on Grid
O(m*n*α(m*n))O(3mn)
FIG. 200 NUMBER OF ISLANDS● INTERACTIVE
visualization loads as you reach it
419. Battleships in a Board
Medium·
DFS - Recursive
O(m*n)O(2mn)
FIG. 419 BATTLESHIPS IN A BOARD● INTERACTIVE
visualization loads as you reach it
694. Number of Distinct Islands
Medium·
DFS - Recursive
O(m*n)O(6*m*n)
FIG. 694 NUMBER OF DISTINCT ISLANDS● INTERACTIVE
visualization loads as you reach it
733. Flood Fill
Easy·
733Flood Fill
DFS - Recursive
O(m*n)O(2mn)
FIG. 733 FLOOD FILL● INTERACTIVE
visualization loads as you reach it
1034. Coloring A Border
Medium·
DFS - Two Phase
O(m*n)O(3mn)
FIG. 1034 COLORING A BORDER● INTERACTIVE
visualization loads as you reach it
463. Island Perimeter
Easy·
DFS - Recursive
O(2mn)O(2mn)
FIG. 463 ISLAND PERIMETER● INTERACTIVE
visualization loads as you reach it
695. Max Area of Island
Medium·
2 Approaches · 2 patterns
DFS - Recursive
O(m*n)O(2mn)
DSU: getSize After Each Union↗ DSU on Grid
O(m*n*α(m*n))O(3mn)
FIG. 695 MAX AREA OF ISLAND● INTERACTIVE
visualization loads as you reach it
3619. Count Islands With Total Value Divisible by K
Medium·
DFS - Recursive
O(m*n)O(2mn)
FIG. 3619 COUNT ISLANDS DIVISIBLE● INTERACTIVE
visualization loads as you reach it
1254. Number of Closed Islands
Medium·
DFS - Recursive
O(m*n)O(2mn)
FIG. 1254 NUMBER OF CLOSED ISLANDS● INTERACTIVE
visualization loads as you reach it
1905. Count Sub Islands
Medium·
DFS - Recursive
O(m*n)O(2mn)
FIG. 1905 COUNT SUB ISLANDS● INTERACTIVE
visualization loads as you reach it
827. Making A Large Island
Hard·
DFS + Island Labeling
O(2mn)O(3mn)
FIG. 827 MAKING A LARGE ISLAND● INTERACTIVE
visualization loads as you reach it
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·
DFS - Recursive
O(2mn)O(mn)
FIG. 130 SURROUNDED REGIONS● INTERACTIVE
visualization loads as you reach it
417. Pacific Atlantic Water Flow
Medium·
DFS - Recursive
O(3*m*n)O(3*m*n)
FIG. 417 PACIFIC ATLANTIC WATER FLOW● INTERACTIVE
visualization loads as you reach it
1020. Number of Enclaves
Medium·
DFS - Recursive
O(2mn)O(2mn)
FIG. 1020 NUMBER OF ENCLAVES● INTERACTIVE
visualization loads as you reach it