Let's play the minesweeper game (Wikipedia, online game)!
You are given an m x n
char matrix board
representing the game board where:
M
' represents an unrevealed mine,E
' represents an unrevealed empty square,B
' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),1
' to '8
') represents how many mines are adjacent to this revealed square, andX
' represents a revealed mine.You are also given an integer array click
where click = [clickr, clickc]
represents the next click position among all the unrevealed squares ('M
' or 'E
').
Return the board after revealing this position according to the following rules:
/**
* @param {character[][]} board
* @param {number[]} click
* @return {character[][]}
*/
var updateBoard = function(board, click) {
// click = n, m
const n = board.length;
const m = board[0].length;
let visited = Array.from(Array(n), () => Array(m).fill(0));
const dx = [-1, -1, -1, 0, 1, 1, 1, 0];
const dy = [-1, 0, 1, 1, 1, 0, -1, -1];
const countMines = (x, y) => {
// 주변 8개에서 지뢰 수 세기
let cnt = 0;
for(let i = 0; i < 8; i++){
let nx = x + dx[i];
let ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] === 'M') {
cnt++;
}
}
return cnt;
}
const bfs = (x, y) => {
if(board[x][y] === 'M'){
board[x][y] = 'X';
return
}
const q = [];
q.push([x, y]);
visited[x][y] = 1;
while(q.length > 0){
const [a, b] = q.shift();
const num = countMines(a, b);
if(num > 0){
board[a][b] = num.toString();
} else {
board[a][b] = 'B';
for(let i = 0; i < 8; i++){
let nx = a + dx[i];
let ny = b + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny] && board[nx][ny] === 'E'){
visited[nx][ny] = 1;
q.push([nx, ny]);
}
}
}
}
}
bfs(click[0], click[1]);
return board;
};