Overview
The flood-fill algorithm starts from a seed pixel and recursively visits neighbouring pixels that share the same colour, repainting them as it goes. It is the backbone of the paint-bucket tool found in image editors as well as a popular exercise in introductory computer-science courses.
Algorithm (Recursive Implementation)
function floodFill(x, y, targetColour, newColour):
if pixel(x, y) is outside canvas: return
if colour(x, y) ≠ targetColour: return
set colour(x, y) ← newColour
floodFill(x+1, y)
floodFill(x-1, y)
floodFill(x, y+1)
floodFill(x, y-1)
The algorithm terminates when all reachable pixels of the target colour have been repainted. In practice an explicit stack/queue is often preferred to avoid blowing the call stack on large fills.
Try it in the Gallery
- Click anywhere in the grid to pour paint.
- Reset to generate a new random mosaic.
- Watch the colour propagate in real-time—depth-first thanks to recursion.
Inspect games/js/demos.js
for a terse but faithful implementation.