1 min read Tweet this post

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.


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] 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.

Solving this problem is very straihtforward.

  1. Walking through all matrix positions.
  2. Check the surrounding cells containing a mine and count all mines in them.
  3. Update current cell with total mines in neighbor, include diagonal neighbor.

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) {
                // if a neighbor is bomb add counter
                if matrix[r][c]{

    return result

Get max row and column matrix and create helper outOfBounds function to check matrix position outside matrix or not.

Create place holder result array.

Iterate through all matrix.

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.

Return result array

cp go practice