Visualize

Pattern visualizer

Flood Fill (Recursion)

This is graph traversal in disguise: each cell is a node, and same-colored neighbors are edges. Recursing outward from the start cell and recoloring as you go — while checking bounds and the original color at every step — naturally stops at any boundary where the color changes, without ever needing to track a separate 'visited' set (the recolor itself IS the visited marker). Animated on: image = [[1,1,1],[1,1,0],[1,0,1]], start=(1,1), newColor=2 — recolor the connected region (shown flattened row-major)..

DFS: recolor, then recurse into all 4 neighbors

time O(rows * cols)space O(rows * cols) recursion stackstep 1 / 8
1
[0]
1
[1]
1
[2]
1
[3]
1
[4]
0
[5]
1
[6]
0
[7]
1
[8]
line 2

Start at (1,1), color=1. Recolor it and every 4-directionally connected cell that shares the same original color.

Pseudocode
1FUNCTION floodFill(image, r, c, newColor):
2 oldColor = image[r][c]
3 FUNCTION dfs(r, c):
4 IF (r,c) is out of bounds or image[r][c] != oldColor: RETURN
5 image[r][c] = newColor
6 dfs into the 4 neighbors: up, down, left, right
7 call dfs(r, c)

← / → step · space play · Home restart

Where to practice Recursion