Skip to content
Ayotl

← Algorithms · Lesson 8/11

Flood fill: the paint bucket

▶ Watch it as a video: one minute with LeIA

Watch on YouTube →

✕
1/10

How far does the bucket paint?

You click the wall with the paint bucket and the whole wall gets painted, but not the roof, or the sky, or the door, even though they're white too. The rule is this: it paints the cells that have the same color as the one you clicked and that you can reach from it going only through cells of that color, up, down, left or right.

That's called flood fill: as if you poured water and the black line were the shore. The door is white, but to get to it you'd have to cross the line.

  • x the line
  • m the wall, 19 cells
leccion.js

$ node leccion.js

Press RUN (or Ctrl+Enter).

What to look at

  • From (6, 6), the ones above and below are line (x); the ones to the right and left are paper.
  • Outside the map you get undefined: ?. keeps it from crashing when you ask for a row that doesn't exist. Since undefined isn't the old color, the edge of the drawing stops the paint by itself.
The whole lesson on one page

How far does the bucket paint?

You click the wall with the paint bucket and the whole wall gets painted, but not the roof, or the sky, or the door, even though they're white too. The rule is this: it paints the cells that have the same color as the one you clicked and that you can reach from it going only through cells of that color, up, down, left or right.

That's called flood fill: as if you poured water and the black line were the shore. The door is white, but to get to it you'd have to cross the line.

  • x the line
  • m the wall, 19 cells
// 'x' is the line and '.', the paper; each row is split into letters so they can be changed
const mapa = [
  ".............",
  "......x......",
  ".....x.x.....",
  "....x...x....",
  "...x.....x...",
  "..xxxxxxxxx..",
  "..x.......x..",
  "..x.xxx...x..",
  "..x.x.x...x..",
  "..x.x.x...x..",
  "..xxxxxxxxx..",
].map((fila) => [...fila]);

// up, right, down, left
const lados = (y, x) => [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]];

// the four neighbors of cell (6, 6), on the wall
for (const [i, j] of lados(6, 6)) console.log(i, j, mapa[i]?.[j]);

// and the ones of a corner of the sky: two fall outside
for (const [i, j] of lados(0, 0)) console.log(i, j, mapa[i]?.[j]);
  • From (6, 6), the ones above and below are line (x); the ones to the right and left are paper.
  • Outside the map you get undefined: ?. keeps it from crashing when you ask for a row that doesn't exist. Since undefined isn't the old color, the edge of the drawing stops the paint by itself.

A stack of things to do

First you note the old color, the one that was where you clicked. You paint that cell and push it onto a stack. Then, while the stack has something: you pop the one on top and look at its four neighbors; the ones that are still the old color get painted and pushed.

When the stack is empty, there's no one left to ask: you're done. The wall comes to 19 cells.

// 'x' is the line and '.', the paper; each row is split into letters so they can be changed
const mapa = [
  ".............",
  "......x......",
  ".....x.x.....",
  "....x...x....",
  "...x.....x...",
  "..xxxxxxxxx..",
  "..x.......x..",
  "..x.xxx...x..",
  "..x.x.x...x..",
  "..x.x.x...x..",
  "..xxxxxxxxx..",
].map((fila) => [...fila]);

// up, right, down, left
const lados = (y, x) => [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]];

function rellenar(f, c, nuevo) {
  const viejo = mapa[f][c];
  if (viejo === nuevo) return;
  const pila = [[f, c]];
  mapa[f][c] = nuevo;
  while (pila.length > 0) {
    const [y, x] = pila.pop();
    for (const [i, j] of lados(y, x))
      if (mapa[i]?.[j] === viejo) {
        mapa[i][j] = nuevo;
        pila.push([i, j]);
      }
  }
}

const ver = () => console.log(mapa.map((fila) => fila.join("")).join("\n"));
const cuantas = (letra) => mapa.flat().filter((l) => l === letra).length;

rellenar(6, 6, "m");
ver();
console.log("painted:", cuantas("m"));
  • The two cells of the door are still .: nobody got to them.
  • Try rellenar(8, 5, "p") to paint the door, or rellenar(5, 5, "x"): clicking the line with its own color does nothing.
  • Click the line with another letter, rellenar(5, 5, "r"): the wall's frame changes, but not the roof's lines. They only touch at the corner, and that matters later on.

Painting is marking

In the maze you had to note who had already been seen. Not here: as soon as a cell is painted, it stops being the old color, so nobody goes in twice. That's why it's painted when it's pushed and not when it's popped: if you left it for later, two neighbors could push the same one.

And that's why if (viejo === nuevo) return; is there. If you paint white what's already white, the painted cell is still the old color: they'd all go in again and again, and it would never end.

// 'x' is the line and '.', the paper; each row is split into letters so they can be changed
const mapa = [
  ".............",
  "......x......",
  ".....x.x.....",
  "....x...x....",
  "...x.....x...",
  "..xxxxxxxxx..",
  "..x.......x..",
  "..x.xxx...x..",
  "..x.x.x...x..",
  "..x.x.x...x..",
  "..xxxxxxxxx..",
].map((fila) => [...fila]);

// up, right, down, left
const lados = (y, x) => [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]];

// the same one, but it paints when POPPING instead of pushing, and counts how many go in
function tarde(f, c, nuevo) {
  const viejo = mapa[f][c];
  const pila = [[f, c]];
  let entraron = 1;
  while (pila.length > 0) {
    const [y, x] = pila.pop();
    mapa[y][x] = nuevo;
    for (const [i, j] of lados(y, x))
      if (mapa[i]?.[j] === viejo) { pila.push([i, j]); entraron++; }
  }
  return entraron;
}

console.log("wall cells: 19");
console.log("pushed onto the stack:", tarde(6, 6, "m"));
  • You get the same picture, but more than 19 go in: some cells were on the stack twice.
  • On a big drawing you'd notice. Painting on push, each cell goes in once and its four sides are looked at: the work grows with the cells painted, O(n).

Four neighbors, not eight

The lines of the roof run diagonally: each black cell touches the next one only at the corner. With four neighbors that's enough to block the way. If you also look at the diagonals (eight neighbors), the paint leaks through the corners and stains the sky.

Eight isn't wrong: it's a different idea of "touching". What matters is knowing which one you want. Minesweeper, for example, opens in all eight.

  • x the line
  • m the wall, 19 cells
  • o the roof, 9 cells
  • h the sky, 73 cells
// 'x' is the line and '.', the paper; each row is split into letters so they can be changed
const mapa = [
  ".............",
  "......x......",
  ".....x.x.....",
  "....x...x....",
  "...x.....x...",
  "..xxxxxxxxx..",
  "..x.......x..",
  "..x.xxx...x..",
  "..x.x.x...x..",
  "..x.x.x...x..",
  "..xxxxxxxxx..",
].map((fila) => [...fila]);

// all eight around it, diagonals included
const lados = (y, x) => [[y - 1, x], [y - 1, x + 1], [y, x + 1], [y + 1, x + 1],
                         [y + 1, x], [y + 1, x - 1], [y, x - 1], [y - 1, x - 1]];

function rellenar(f, c, nuevo) {
  const viejo = mapa[f][c];
  if (viejo === nuevo) return;
  const pila = [[f, c]];
  mapa[f][c] = nuevo;
  while (pila.length > 0) {
    const [y, x] = pila.pop();
    for (const [i, j] of lados(y, x))
      if (mapa[i]?.[j] === viejo) {
        mapa[i][j] = nuevo;
        pila.push([i, j]);
      }
  }
}

const ver = () => console.log(mapa.map((fila) => fila.join("")).join("\n"));
const cuantas = (letra) => mapa.flat().filter((l) => l === letra).length;

rellenar(4, 6, "o");   // the roof
ver();
console.log("painted:", cuantas("o"));
  • It paints 82: the roof's 9 and the sky's 73. With four neighbors it'd be 9.
  • The wall is safe: its corners are closed with black cells that touch side by side.

With a queue, a stack, or calling itself

If instead of popping the top one you take the first one in (a queue), the paint moves in even waves, like the maze's BFS. With the stack it dives deep on one side and then comes back. The order changes; the final picture is the same, because every reachable cell gets painted, whatever the order.

You can also write it with recursion: paint, then call yourself with your four neighbors. It's six lines, but now the stack is the call stack, and that one is small: on a big drawing it overflows.

// up, right, down, left
const lados = (y, x) => [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]];

let mapa;
function recursivo(f, c, nuevo, viejo = mapa[f][c]) {
  if (viejo === nuevo || mapa[f]?.[c] !== viejo) return;
  mapa[f][c] = nuevo;
  for (const [i, j] of lados(f, c)) recursivo(i, j, nuevo, viejo);
}

function rellenar(f, c, nuevo) {
  const viejo = mapa[f][c];
  if (viejo === nuevo) return;
  const pila = [[f, c]];
  mapa[f][c] = nuevo;
  while (pila.length > 0) {
    const [y, x] = pila.pop();
    for (const [i, j] of lados(y, x))
      if (mapa[i]?.[j] === viejo) {
        mapa[i][j] = nuevo;
        pila.push([i, j]);
      }
  }
}

const lienzo = (n) => Array.from({ length: n }, () => Array(n).fill("."));
const cuantas = () => mapa.flat().filter((l) => l === "m").length;

mapa = lienzo(20);
recursivo(0, 0, "m");
console.log("20 x 20, recursive:", cuantas());

mapa = lienzo(400);
try {
  recursivo(0, 0, "m");
  console.log("400 x 400, recursive:", cuantas());
} catch (e) {
  console.log("400 x 400, recursive:", e.message);
}

mapa = lienzo(400);
rellenar(0, 0, "m");
console.log("400 x 400, with a stack:", cuantas());
  • On the 20 x 20 one both work. On the 400 x 400 one the recursive version runs out of call stack (the message depends on the browser); ours paints all 160,000.
  • To see it in waves, change pila.pop() to pila.shift(): the result doesn't change.

What it's for: Qix and counting islands

In Qix, on Daily Challenge, when you close a line the game fills each unclaimed piece, with a stack like this one, and gives it a number. Then it checks which ones the creature is in: those stay free and the rest are yours.

The same works for counting regions: go over the cells and, each time you find one that's not painted, fill all of it and add one. It's the "number of islands" problem, an interview classic.

// 'x' is the line and '.', the paper; each row is split into letters so they can be changed
const mapa = [
  ".............",
  "......x......",
  ".....x.x.....",
  "....x...x....",
  "...x.....x...",
  "..xxxxxxxxx..",
  "..x.......x..",
  "..x.xxx...x..",
  "..x.x.x...x..",
  "..x.x.x...x..",
  "..xxxxxxxxx..",
].map((fila) => [...fila]);

// up, right, down, left
const lados = (y, x) => [[y - 1, x], [y, x + 1], [y + 1, x], [y, x - 1]];

function rellenar(f, c, nuevo) {
  const viejo = mapa[f][c];
  if (viejo === nuevo) return;
  const pila = [[f, c]];
  mapa[f][c] = nuevo;
  while (pila.length > 0) {
    const [y, x] = pila.pop();
    for (const [i, j] of lados(y, x))
      if (mapa[i]?.[j] === viejo) {
        mapa[i][j] = nuevo;
        pila.push([i, j]);
      }
  }
}

const ver = () => console.log(mapa.map((fila) => fila.join("")).join("\n"));
const cuantas = (letra) => mapa.flat().filter((l) => l === letra).length;

let regiones = 0;
for (let f = 0; f < mapa.length; f++)
  for (let c = 0; c < mapa[f].length; c++)
    if (mapa[f][c] === ".") {
      regiones++;
      rellenar(f, c, String(regiones));   // each piece, with its number
    }
ver();
console.log("white pieces:", regiones);
  • There are four: the sky, the roof, the wall and the door.
  • The for loops go over every cell, but each one is painted only once: the total work is still O(n).

Practice with a video challenge

Further reading