Open Tcdian opened 3 years ago
/**
* @param {character[][]} board
* @param {number[]} click
* @return {character[][]}
*/
var updateBoard = function(board, click) {
const [x, y] = click;
if (board[x][y] === 'M') {
board[x][y] = 'X';
return board;
}
bfs([x, y]);
return board;
function bfs(start) {
const queue = [start];
const directionX = [-1, -1, -1, 0, 1, 1, 1, 0];
const directionY = [-1, 0, 1, 1, 1, 0, -1, -1];
while (queue.length !== 0) {
const [x, y] = queue.shift();
const nexts = [];
let MCounts = 0;
for (let i = 0; i < 8; i++) {
const nextX = x + directionX[i];
const nextY = y + directionY[i];
if (
nextX >= 0 && nextX < board.length
&& nextY >= 0 && nextY < board[0].length
) {
if (board[nextX][nextY] === 'M') {
MCounts += 1;
}
if (board[nextX][nextY] === 'E') {
nexts.push([nextX, nextY]);
}
}
}
if (MCounts !== 0) {
board[x][y] = String(MCounts);
} else {
board[x][y] = 'B';
nexts.forEach(([nextX, nextY]) => { board[nextX][nextY] = 'W'; });
queue.push(...nexts);
}
}
}
};
function updateBoard(board: string[][], click: number[]): string[][] {
const [x, y] = click;
if (board[x][y] === 'M') {
board[x][y] = 'X';
return board;
}
bfs([x, y]);
return board;
function bfs(start: [number, number]) {
const queue: [number, number][] = [start];
const directionX = [-1, -1, -1, 0, 1, 1, 1, 0];
const directionY = [-1, 0, 1, 1, 1, 0, -1, -1];
while (queue.length !== 0) {
const [x, y] = queue.shift() as [number, number];
const nexts: [number, number][] = [];
let MCounts = 0;
for (let i = 0; i < 8; i++) {
const nextX = x + directionX[i];
const nextY = y + directionY[i];
if (
nextX >= 0 && nextX < board.length
&& nextY >= 0 && nextY < board[0].length
) {
if (board[nextX][nextY] === 'M') {
MCounts += 1;
}
if (board[nextX][nextY] === 'E') {
nexts.push([nextX, nextY]);
}
}
}
if (MCounts !== 0) {
board[x][y] = String(MCounts);
} else {
board[x][y] = 'B';
nexts.forEach(([nextX, nextY]) => { board[nextX][nextY] = 'W'; });
queue.push(...nexts);
}
}
}
};
529. Minesweeper
让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
Example 1
Example 2
Note