Minesweeper
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
- 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]
]
Check out the image below for better understanding:
Image Credit: CodeSignal |
Solution
py
def minesweeper(matrix):
rows = len(matrix)
cols = len(matrix[0])
result = [[0 for _ in range(cols)] for _ in range(rows)]
for row in range(rows):
for col in range(cols):
if matrix[row][col]:
for i in range(max(0, row - 1), min(rows, row + 2)):
for j in range(max(0, col - 1), min(cols, col + 2)):
if i != row or j != col:
result[i][j] += 1
return result
print(minesweeper([
[True, False, False],
[False, True, False],
[False, False, False]
]))
js
function minesweeper(matrix) {
const result = [];
for (let i = 0; i < matrix.length; i++) {
result[i] = [];
for (let j = 0; j < matrix[i].length; j++) {
let count = 0;
if (i > 0 && j > 0 && matrix[i - 1][j - 1]) count++;
if (i > 0 && matrix[i - 1][j]) count++;
if (i > 0 && j < matrix[i].length - 1 && matrix[i - 1][j + 1]) count++;
if (j > 0 && matrix[i][j - 1]) count++;
if (j < matrix[i].length - 1 && matrix[i][j + 1]) count++;
if (i < matrix.length - 1 && j > 0 && matrix[i + 1][j - 1]) count++;
if (i < matrix.length - 1 && matrix[i + 1][j]) count++;
if (i < matrix.length - 1 && j < matrix[i].length - 1 && matrix[i + 1][j + 1]) count++;
result[i][j] = count;
}
}
return result;
}
console.log(
minesweeper([
[True, False, False],
[False, True, False],
[False, False, False],
])
);