-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0529-minesweeper.js
More file actions
74 lines (66 loc) · 1.76 KB
/
0529-minesweeper.js
File metadata and controls
74 lines (66 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Minesweeper
* Time Complexity: O(M*N)
* Space Complexity: O(M*N)
*/
var updateBoard = function (board, click) {
const clickedRow = click[0];
const clickedCol = click[1];
const boardRows = board.length;
const boardCols = board[0].length;
const adjacentDirections = [
[-1, -1],
[-1, 0],
[-1, 1],
[0, -1],
[0, 1],
[1, -1],
[1, 0],
[1, 1],
];
if (board[clickedRow][clickedCol] === "M") {
board[clickedRow][clickedCol] = "X";
return board;
}
function dfsReveal(currentRow, currentCol) {
if (
currentRow < 0 ||
currentRow >= boardRows ||
currentCol < 0 ||
currentCol >= boardCols ||
board[currentRow][currentCol] !== "E"
) {
return;
}
let mineCounter = 0;
for (const directionPair of adjacentDirections) {
const rowDelta = directionPair[0];
const colDelta = directionPair[1];
const nextCellRow = currentRow + rowDelta;
const nextCellCol = currentCol + colDelta;
if (
nextCellRow >= 0 &&
nextCellRow < boardRows &&
nextCellCol >= 0 &&
nextCellCol < boardCols &&
board[nextCellRow][nextCellCol] === "M"
) {
mineCounter++;
}
}
if (mineCounter > 0) {
board[currentRow][currentCol] = mineCounter.toString();
} else {
board[currentRow][currentCol] = "B";
for (const otherDirectionPair of adjacentDirections) {
const otherRowDelta = otherDirectionPair[0];
const otherColDelta = otherDirectionPair[1];
const nextExploreRow = currentRow + otherRowDelta;
const nextExploreCol = currentCol + otherColDelta;
dfsReveal(nextExploreRow, nextExploreCol);
}
}
}
dfsReveal(clickedRow, clickedCol);
return board;
};