Workshop › Minesweeper › Step 15 of 26

Flood fill

What we are doing

A 0 means "no mines around me", so all its neighbours are safe to open, and if one of them is a 0 too, its neighbours are safe as well. This spreading is a flood fill. We keep our own list of cells to open, a stack, and loop until it is empty.

```js
// Flood fill with our own stack: open the cell, and keep opening around every empty (0) cell.
const stack = [start]
while (stack.length > 0) {
  const cell = stack.pop()
  if (cell.revealed) continue
  cell.revealed = true
  if (cell.count === 0) {
    for (const next of neighbors(cell)) {
      if (!next.revealed && !next.mine) stack.push(next)
    }
  }
}
```

What it means

Your turn

In reveal, replace start.revealed = true with the comment and the flood fill. Press Run and click.

Skills: Loops, Arrays and objects

All steps

  1. A grid of cell objects
  2. The canvas and the pen
  3. Draw the field
  4. Draw every frame
  5. Neighbours
  6. Mines, but not under the first click
  7. Shuffle the candidates
  8. Count the mines around
  9. Open a cell
  10. Open cells look different
  11. Coloured numbers
  12. Click to open
  13. Stepping on a mine
  14. Show the mines
  15. Flood fill
  16. Flags with the right button
  17. A flag protects its cell
  18. Draw the flags
  19. Mines left
  20. Winning
  21. The end and a new game
  22. What time is it?
  23. The clock
  24. Stop the clock
  25. The best time
  26. Build it yourself: wrong flags