Minesweeper

Description


In the popular Minesweeper game you have a board with some mines and those cells that don’t contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup.

Example

matrix = [[true, false, false], [false, true, false], [false, false, false]]

the output should be

minesweeper(matrix) = [[1, 2, 1], [2, 1, 1], [1, 1, 1]]

Check out the image below for better understanding:

Input/Output

  • [execution time limit] 4 seconds (js)

  • [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.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function minesweeper(matrix) {
  var adjacents = ([i, j]) => [
    [i - 1, j - 1],
    [i - 1, j],
    [i - 1, j + 1],
    [i, j - 1],
    [i, j + 1],
    [i + 1, j - 1],
    [i + 1, j],
    [i + 1, j + 1],
  ];
  var hintsMatrix = matrix.map((r) => r.map((_) => 0));

  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j]) {
        var myAd = adjacents([i, j]);
        for (var k = 0; k < 8; k++) {
          if (
            myAd[k][0] >= 0 &&
            myAd[k][1] >= 0 &&
            myAd[k][0] < matrix.length &&
            myAd[k][1] < matrix[i].length
          ) {
            hintsMatrix[myAd[k][0]][myAd[k][1]]++;
          }
        }
      }
    }
  }

  return hintsMatrix;
}