Minesweeper
Time limit1sMemory limit128 MB
Given a partially revealed Minesweeper grid, mark each unrevealed cell as definitely a mine, definitely safe, or undetermined across all consistent arrangements.
- Level
Medium7 of 10
- Topics
- Backtracking, Brute force
- Solved
- No attempts yet
Problem
In the game of Minesweeper you are shown a grid, and some cells contain mines. When you reveal a cell that you believe is safe, one of two things happens: if it held a mine you lose; otherwise the cell shows how many of its up to eight neighbours (including diagonals) contain mines.
Given a partially revealed Minesweeper grid, decide for every unrevealed cell whether it must contain a mine, cannot contain a mine, or is undetermined by the available information.
Input
The first line contains two integers, the width and the height of the grid (, ).
Each of the next lines is one row of the grid:
- a digit
0–8is a revealed cell that contains no mine, and the digit is the number of its neighbours (including diagonals) that contain mines; - a period
.is an unrevealed cell.
The number of mine arrangements consistent with the revealed cells is at most a few tens of thousands, and at least one such arrangement is guaranteed to exist.
Output
Print the grid, one row per line, using the same layout as the input. For each cell:
- a revealed cell keeps its digit;
- an unrevealed cell that contains a mine in every consistent arrangement becomes
*; - an unrevealed cell that is safe in every consistent arrangement becomes a single space
; - any other unrevealed cell (its contents cannot be determined, or it is not adjacent to any revealed cell) stays
..