Minesweeper LeetCode solution in JavaScript

1
var updateBoard = function (board, click) {
2
const rows = board.length;
3
const cols = board[0].length;
4
dfs(click[0], click[1]);
5
return board;
6

7
function dfs(i, j) {
8
if (!board[i][j]) return;
9
if (board[i][j] === "M") {
10
board[i][j] = "X";
11
return;
12
}
13
if (board[i][j] !== "E") return;
14

15
const mines = checkForMine(i, j); // Check for mines
16

17
if (mines) {
18
board[i][j] = mines.toString();
19
return;
20
} else {
21
// If we haven't got mines, check another cells
22
board[i][j] = "B";
23
for (let x = Math.max(i - 1, 0); x < Math.min(i + 2, rows); x++) {
24
for (let y = Math.max(j - 1, 0); y < Math.min(j + 2, cols); y++) {
25
dfs(x, y);
26
}
27
}
28
}
29
}
30

31
function checkForMine(x, y) {
32
let mines = 0;
33
for (let i = Math.max(x - 1, 0); i < Math.min(x + 2, rows); i++) {
34
for (let j = Math.max(y - 1, 0); j < Math.min(y + 2, cols); j++) {
35
if (board[i][j] === "M") mines++;
36
}
37
}
38
return mines;
39
}
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0