I am designing a Minesweeper game, yet I can't find the algorithm on how to board "opens up". If you have ever played Minesweeper, the first click or so will display lots of the tiles. What is the algorithm behind it?
Asked
Active
Viewed 3,481 times
4
-
It's just good ol' recursion. User clicks square (x, y)? `show(x, y)`. Inside the function, it shows the square, and, *if the square is blank*, calls `show(x-1, y)`, `show(x+1, y)`, `show(x, y-1)` and `show(x, y+1)`. (And maybe the diagonals too, I can't remember now.) – j_random_hacker Oct 28 '13 at 11:36
-
Be careful with forever loops. – ChronoTrigger Oct 28 '13 at 11:38
2 Answers
4
You could use a flood-fill algorithm, but only for cells without any neighbouring bombs (would display a "0" or no value), and their surrounding cells.
Some pseudo-code:
floodFill(cell)
if not cell.isOpen
cell.open()
if not cell.hasNeighbouringBombs
for each neighbour n of cell
floodFill(n)
Note how this is different from the 'normal' flood-fill algorithm:
floodFill(cell)
if not cell.hasNeighbouringBombs and not cell.isOpen
cell.open()
for each neighbour n of cell
floodFill(n)
The reason for the difference can be seen in this example:
1 1 2
2 0 3
1 2 3
The normal flood-fill algorithm would fill only the 0
, but we want to fill all of the above, thus we should check hasNeighbouringBombs
only after we open the current cell.
Note that if you start off clicking on a cell with a non-zero value, no other cells are opened up (at least on most versions of the game) - this would be taken care of with the above algorithm.

Bernhard Barker
- 54,589
- 14
- 104
- 138
-
And if you start off clicking on a mine, the mine is moved to another location, so that you don't die on your first click. – Teepeemm Oct 28 '13 at 17:18
-
@Teepeemm Depending on the game - some are happy letting you click on a mine to start. But generating the game based on the first click seems like a better idea (but obviously more complex). – Bernhard Barker Oct 28 '13 at 17:20
-
@Dukeling I don't quite understand what `!open` means. Please could you elaborate on the different uses of `open` in your psuedocode? – LazySloth13 Oct 28 '13 at 20:40
-
@Lewis I hope `cell.open` and `cell.isOpen` will make more sense. Changed it. – Bernhard Barker Oct 28 '13 at 21:16
-
This implementation can result in StackOverflowException if there are too many closed adjacent cells to be visited – Bruno Negrão Zica Jul 09 '21 at 23:28
-