|
| 1 | +/** |
| 2 | + * 529. Minesweeper |
| 3 | + * https://leetcode.com/problems/minesweeper/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Let's play the minesweeper game (Wikipedia, online game)! |
| 7 | + * |
| 8 | + * You are given an m x n char matrix board representing the game board where: |
| 9 | + * - 'M' represents an unrevealed mine, |
| 10 | + * - 'E' represents an unrevealed empty square, |
| 11 | + * - 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, |
| 12 | + * left, right, and all 4 diagonals), |
| 13 | + * - digit ('1' to '8') represents how many mines are adjacent to this revealed square, and |
| 14 | + * - 'X' represents a revealed mine. |
| 15 | + * |
| 16 | + * You are also given an integer array click where click = [clickr, clickc] represents the |
| 17 | + * next click position among all the unrevealed squares ('M' or 'E'). |
| 18 | + * |
| 19 | + * Return the board after revealing this position according to the following rules: |
| 20 | + * 1. If a mine 'M' is revealed, then the game is over. You should change it to 'X'. |
| 21 | + * 2. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed |
| 22 | + * blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. |
| 23 | + * 3. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a |
| 24 | + * digit ('1' to '8') representing the number of adjacent mines. |
| 25 | + * 4. Return the board when no more squares will be revealed. |
| 26 | + */ |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {character[][]} board |
| 30 | + * @param {number[]} click |
| 31 | + * @return {character[][]} |
| 32 | + */ |
| 33 | +var updateBoard = function(board, click) { |
| 34 | + const [row, col] = click; |
| 35 | + const rows = board.length; |
| 36 | + const cols = board[0].length; |
| 37 | + const directions = [ |
| 38 | + [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] |
| 39 | + ]; |
| 40 | + |
| 41 | + if (board[row][col] === 'M') { |
| 42 | + board[row][col] = 'X'; |
| 43 | + return board; |
| 44 | + } |
| 45 | + |
| 46 | + dfs(row, col); |
| 47 | + return board; |
| 48 | + |
| 49 | + function dfs(r, c) { |
| 50 | + if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== 'E') return; |
| 51 | + |
| 52 | + let mines = 0; |
| 53 | + for (const [dr, dc] of directions) { |
| 54 | + const nr = r + dr; |
| 55 | + const nc = c + dc; |
| 56 | + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] === 'M') { |
| 57 | + mines++; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + board[r][c] = mines > 0 ? mines.toString() : 'B'; |
| 62 | + if (mines === 0) { |
| 63 | + for (const [dr, dc] of directions) { |
| 64 | + dfs(r + dr, c + dc); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +}; |
0 commit comments