← Games

Game Hub Articles

All articles
Home › Articles
🌊

The flood fill algorithm: how the paint bucket works

By Noam · 4 December 2026 · 7 min read

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

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.

▶ Play Color FloodAll games

More articles

🔦 How mirrors bend light: the science behind Laser MirrorsWhy light bounces off a mirror at the same angle it arrives, how periscopes and lasers use it, and how a 45-degree mirror turns a beam around a corner.✈️ How paper planes fly: lift, drag and the secret of glidingThe four forces on every plane, why a paper plane glides instead of dropping, and simple tips for making one that flies further.🔟 Number bonds to 10: the maths trick behind Make TenWhat number bonds are, why knowing pairs that make 10 makes all mental maths faster, and fun ways to practise them.