The flood fill algorithm: how the paint bucket works
Click the paint bucket in a drawing app and a whole shape fills with colour in an instant, stopping exactly at the edges. The trick behind it is called flood fill, and it's also the heart of Color Flood.
The idea
Start at the pixel you clicked. Colour it. Then look at its four neighbours: up, down, left and right. Any neighbour that had the same old colour gets coloured too, and then you look at its neighbours, and so on. The colour spreads like water flowing into every connected space, and stops at any pixel of a different colour, just like water stops at a wall.
In Color Flood
In the game, your area starts in the top-left corner. When you choose a new colour, the game repaints your area, then floods outwards to grab every touching square that already had the new colour. The white outline you see is exactly the set of squares the flood fill reached.
Writing it in JavaScript
Here's a simple flood fill for a grid stored as rows of numbers. It uses a list of squares still to visit, often called a queue or stack.
function floodFill(grid, startX, startY, newColor) {
const oldColor = grid[startY][startX];
if (oldColor === newColor) return;
const todo = [[startX, startY]];
while (todo.length) {
const [x, y] = todo.pop();
if (y < 0 || y >= grid.length || x < 0 || x >= grid[0].length) continue;
if (grid[y][x] !== oldColor) continue;
grid[y][x] = newColor;
todo.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
}
}
Each square is coloured once and then never matches the old colour again, so the loop always finishes.
Four neighbours or eight?
The code above only spreads up, down, left and right. Some programs also spread diagonally, using eight neighbours. That fills more, but it can leak through diagonal gaps in a thin outline. Most paint programs use four.
Where else it's used
- Mine-finding games: clicking an empty square opens a whole area at once. That's flood fill.
- Puzzle games: games that clear groups of matching tiles use it to find the group.
- Maps and mazes: finding every room you can reach from a starting point is the same algorithm.
- Photo editing: the "magic wand" selection tool picks a region of similar colours with a version of it.
Strategy tip
Knowing how flood fill works helps in Color Flood: your next move can only reach colours that are touching your current edge. Grow towards the middle early so your edge touches as many colours as possible. For a bigger look at how games use code, read how browser games work.