529. Minesweeper

Let's play the minesweeper game (Wikipedia,online game)!

You are given a 2D char matrix representing the game board.'M'represents anunrevealedmine,'E'represents anunrevealedempty square,'B'represents arevealedblank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines,digit('1' to '8') represents how many mines are adjacent to thisrevealedsquare, and finally'X'represents arevealedmine.

Now given the next click position (row and column indices) among all theunrevealedsquares ('M' or 'E'), return the board after revealing this position according to the following rules:

  1. If a mine ('M') is revealed, then the game is over - change it to 'X' .
  2. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
  3. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
  4. Return the board when no more squares will be revealed.
class Solution {
    public char[][] updateBoard(char[][] board, int[] click) {
        int x = click[0], y = click[1];

        if (board[x][y] == 'M'){
            board[x][y] = 'X';
        }
        else{
            int count = 0;

            for (int i = -1; i < 2; i++){
                for (int j = -1; j < 2; j++){
                    if (i == 0 && j == 0) continue;
                    int xx = x + i;
                    int yy = y + j;

                    if (xx < 0 || xx >= board.length || yy < 0 || yy >= board[0].length) continue;

                    if (board[xx][yy] == 'M') count++;
                }
            }

            if (count > 0){
                board[x][y] = (char)('0' + count);
            }
            else{
                board[x][y] = 'B';

                for (int i = -1; i < 2; i++){
                    for (int j = -1; j < 2; j++){
                        if (i == 0 && j == 0) continue;
                        int xx = x + i;
                        int yy = y + j;

                        if (xx < 0 || xx >= board.length || yy < 0 || yy >= board[0].length) continue;

                        if (board[xx][yy] == 'E') updateBoard(board, new int[]{xx, yy});
                    }
                }
            }
        }

        return board;
    }
}

results for ""

    No results matching ""