Straightforward Java Solution


  • 0
    W
    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            int i = click[0];
            int j = click[1];
            
            if (board[i][j] == 'M') {
                board[i][j] = 'X';
                return board;
            }
            
            unrevealSquares(board, i, j); 
            return board;
        }
        
        private void unrevealSquares(char[][] board, int i, int j) {
            if (i < 0 || j < 0 || i == board.length || j == board[0].length || board[i][j] != 'E') return;
            
            int adjacent = adjacentMines(board, i, j);
            if (adjacent > 0) {
                board[i][j] = (char) (adjacent + '0');
            } else {
                board[i][j] = 'B';
                unrevealSquares(board, i-1, j);
                unrevealSquares(board, i, j-1);
                unrevealSquares(board, i+1, j);
                unrevealSquares(board, i, j+1);
                unrevealSquares(board, i-1, j-1);
                unrevealSquares(board, i-1, j+1);
                unrevealSquares(board, i+1, j-1);
                unrevealSquares(board, i+1, j+1);
            }
        }
        
        private int adjacentMines(char[][] board, int i, int j) {
            int m = board.length;
            int n = board[0].length;
            int count = 0;
            
            if (i > 0 && board[i-1][j] == 'M') count++;
            if (j > 0 && board[i][j-1] == 'M') count++;
            if (i < m-1 && board[i+1][j] == 'M') count++;
            if (j < n-1 && board[i][j+1] == 'M') count++;
            
            if (i > 0 && j > 0 && board[i-1][j-1] == 'M') count++;
            if (i < m-1 && j < n-1 && board[i+1][j+1] == 'M') count++;
            if (i > 0 && j < n-1 && board[i-1][j+1] == 'M') count++;
            if (j > 0 && i < m-1 && board[i+1][j-1] == 'M') count++;
            
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.