Minesweeper
January 19, 2023
Problem
In the game of Minesweeper, the player is presented with a board which contains some mines and cells that don't have mines. The cells that don't contain a mine have a number in them that represents the total number of mines in the neighboring cells. The goal is to create a Minesweeper game setup, starting with an initial arrangement of mines on the board.
Example
For
matrix = [[true, false, false], [false, true, false], [false, false, false]]
the output should be
solution(matrix) = [[1, 2, 1], [2, 1, 1], [1, 1, 1]]
Input/Output
[input] array.array.boolean matrix
A non-empty rectangular matrix consisting of boolean values - true if the corresponding cell contains a mine, false otherwise.
Guaranteed constraints:
2 ≤ matrix.length ≤ 100
,
2 ≤ matrix[0].length ≤ 100
.
[output] array.array.integer
Rectangular matrix of the same size as matrix each cell of which contains an integer equal to the number of mines in the neighboring cells. Two cells are called neighboring if they share at least one corner.
Solution
Solving this problem is very straihtforward.
- Walking through all matrix positions.
- Check the surrounding cells containing a mine and count all mines in them.
- Update current cell with total mines in neighbor, include diagonal neighbor.
Step 1
Define all direction to check the neighbor values.
Step 2
Get max row and column matrix and create helper outOfBounds
function to check matrix position outside matrix or not.
Step 3
Create place holder result array.
Step 4
Iterate through all matrix.
Step 5
Find the neighbor with bomb:
- if neighbor is out of bounds, ignore
- every a bomb that found in the neighbor, increase 1 value to the current position.
Step 6
Return result
array