跳到主要内容

529.扫雷游戏

链接:529.扫雷游戏
难度:Medium
标签:深度优先搜索、广度优先搜索、数组、矩阵
简介:让我们一起来玩扫雷游戏!

题解 1 - typescript

  • 编辑时间:2020-08-20
  • 执行用时:200ms
  • 内存消耗:46MB
  • 编程语言:typescript
  • 解法介绍:深度遍历。
function updateBoard(board: string[][], click: number[]): string[][] {
const rowLen = board.length;
const colLen = board[0].length;
console.log(rowLen, colLen);
const set = new Set<string>();
const format = (row: number, col: number) => `${row}:${col}`;
dfs(click[0], click[1]);
return board;
function countMine(row: number, col: number): number {
let num = 0;
// top
if (row !== 0 && col !== 0 && isMine(row - 1, col - 1)) num++;
if (row !== 0 && isMine(row - 1, col)) num++;
if (row !== 0 && col !== colLen - 1 && isMine(row - 1, col + 1)) num++;
// mid
if (col !== 0 && isMine(row, col - 1)) num++;
if (col !== colLen - 1 && isMine(row, col + 1)) num++;
// bottom
if (row !== rowLen - 1 && col !== 0 && isMine(row + 1, col - 1)) num++;
if (row !== rowLen - 1 && isMine(row + 1, col)) num++;
if (row !== rowLen - 1 && col !== colLen - 1 && isMine(row + 1, col + 1)) num++;
return num;
}
function isMine(row: number, col: number): boolean {
return board[row][col] === 'M';
}
function dfs(row: number, col: number): void {
const formatName = format(row, col);
if (set.has(formatName)) return;
else set.add(formatName);
if (isMine(row, col)) {
board[row][col] = 'X';
} else if (countMine(row, col) > 0) {
board[row][col] = countMine(row, col) + '';
} else {
console.log(row, col);
board[row][col] = 'B';
// top
if (row !== 0 && col !== 0) dfs(row - 1, col - 1);
if (row !== 0) dfs(row - 1, col);
if (row !== 0 && col !== colLen - 1) dfs(row - 1, col + 1);
// mid
if (col !== 0) dfs(row, col - 1);
if (col !== colLen - 1) dfs(row, col + 1);
// bottom
if (row !== rowLen - 1 && col !== 0) dfs(row + 1, col - 1);
if (row !== rowLen - 1) dfs(row + 1, col);
if (row !== rowLen - 1 && col !== colLen - 1) dfs(row + 1, col + 1);
}
}
}