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.
func solution(matrix [][]bool) [][]int {
// all directions, including diagonal
allDirections := [][2]int{
{-1, -1}, // diag upper left
{0, -1}, // left
{1, -1}, // diag lower left
{-1, 0}, // up
{1, 0}, // down
{-1, 1}, // diag upper right
{0, 1}, // right
{1, 1}, // diag lower right
}
maxRow, maxCol := len(matrix), len(matrix[0])
// helper func to check bounds of a position in the grid
outOfBounds := func(r, c int) bool {
return r < 0 || r >= maxRow || c >= maxCol || c < 0
}
result:=make([][]int, maxRow)
for row := range matrix{
result[row] = make([]int, maxCol)
for col:= range matrix[row]{
for _, coords := range allDirections {
r,c := coords[0]+row,coords[1]+col
if outOfBounds(r,c) {
continue
}
// if a neighbor is bomb add counter
if matrix[r][c]{
result[row][col]+=1
}
}
}
}
return result
}
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