Workshop › Minesweeper › Step 15 of 26
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)
}
}
}
```while (condition) repeats as long as the condition is true: here, while cells are waiting.pop() takes the last cell off the stack. A cell may have been added twice; continue skips it if already open.0 cells spread. Numbered cells are opened but stop the flood, which is why an open area has a border of
numbers.reveal calling itself) would also work on a small board, but a huge empty board could make thousands of
nested calls and overflow the call stack; our own list never does.In reveal, replace start.revealed = true with the comment and the flood fill. Press Run and click.
Skills: Loops, Arrays and objects
← Show the mines Flags with the right button →