Algorithms · Visualized
Matrix: Recolour (Flood Fill)
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Given a starting cell in a grid (like the 'paint bucket' tool in image editors), changes the color of that cell and all connected cells of the same original color, spreading outward through up/down/left/right neighbors until the connected region is fully recolored. Time: O(rows × cols) average, O(rows × cols) — entire grid is one connected region worst; space: O(rows × cols) — recursion stack or BFS queue in the worst case.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Recolour (Flood Fill)
Matrix / 2D ArrayGiven a starting cell in a grid (like the 'paint bucket' tool in image editors), changes the color of that cell and all connected cells of the same original color, spreading outward through up/down/left/right neighbors until the connected region is fully recolored.
How Recolour (Flood Fill) Works
- Record the original color of the starting cell, and check that the new color is actually different (to avoid infinite loops if they're the same).
- Use a recursive function (or a queue for an iterative BFS approach) starting from the given cell.
- If the current cell is out of bounds, or its color doesn't match the original color, stop this branch.
- Otherwise, change the current cell's color to the new color, then recurse (or enqueue) into its four neighbors (up, down, left, right).
- This spreads outward until every connected cell of the original color has been recolored.
Recolour (Flood Fill) Worked Example
Input: {grid: [[1, 1, 1], [1, 1, 0], [1, 0, 1]], start: [1, 1], newColor: 2}
Start at (1,1), original color=1. Recolor (1,1) to 2. Check neighbors: (0,1)=1 matches → recolor to 2, spread further. (1,0)=1 matches → recolor to 2. (1,2)=0 doesn't match → skip. (2,1)=0 doesn't match → skip. Continue spreading from newly recolored cells until the whole connected region of 1s is turned into 2s: [[2,2,2],[2,2,0],[2,0,1]].
def flood_fill(m, sr, sc, color):
start = m[sr][sc]
if start == color:
return m
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
if not (0 <= r < len(m) and 0 <= c < len(m[0])) or m[r][c] != start:
continue
m[r][c] = color
stack += [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]
return mBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Recolour (Flood Fill) Time & Space Complexity
When to Use Recolour (Flood Fill)
- The 'paint bucket' / fill tool in image editing software.
- Foundation for region-based problems like Number of Islands and Max Area of Island.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.