Tino APCS

Recursive Reveal Algorithm

This page accompanies JavaFX Lab 7.2 ConsoleMinesweeper

Overview

An important part of Minesweeper is writing a recursive reveal method so that when a user clicks a cell it is revealed along with a recursive reveal of its 8 neighbors.

The images below show the result of revealing cell (0, 0), which in turn calls reveal on its 8 neighbors, which in turn calls reveal on each of those cells' 8 neighbors, etc. until out of bounds is reached or a cell is not blank. That's why recursion ends at the boundaries and the numbered cells (which are not blank).

     

Algorithm

When user clicks on a cell...
If the cell hasn't yet been revealed, reveal it.
If the bottom layer of the cell is a mine, game over.
Otherwise if the bottom layer of the cell is blank (no adjacent mines),
then recursively reveal each its 8 neighbors if they are within bounds and haven't been revealed.

Pay attention to the algorithm conditions. If you miss any of them, your code may end up stuck in infinite recursion. In particular, you shouldn't recurse on cells that have already been revealed because it will lead to the same cell being checked repeatedly and cause a stack overflow. Also, it's possible to change the order of some steps. For example, you could first check if a cell is out of bounds and if so then return (quit the method) at the very beginning.

Backtracking Video

Here's a video explaining recursive flood fill, which is the same idea as minesweeper's recursive reveal.

Dark Mode

Outline