Java clean DFS recursive beat 90%


  • 0
    J
    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            if (board.length == 0 || board[0].length == 0) return null;
            int i = click[0];
            int j = click[1];
            if (board[i][j] == 'M') {
                board[i][j] = 'X';
            } else {
                clickEmpty(i, j, board);
            }
            return board;
        }
        
        private void clickEmpty(int i, int j, char[][] board) {
            char mines = '0';
            int[] di = {-1, -1, -1, 0, 0, 1, 1, 1};
            int[] dj = {-1, 0, 1, -1, 1, -1, 0, 1};
            for (int k = 0; k < 8; k++) {
                int ii = i + di[k];
                int jj = j + dj[k];
                if (isValid(board, ii, jj, 'M')) {
                    mines++;
                }
            }
            board[i][j] = (mines == '0') ? 'B' : mines;
            if (mines == '0') {
                for (int k = 0; k < 8; k++) {
                    int ii = i + di[k];
                    int jj = j + dj[k];
                    if (isValid(board, ii, jj, 'E')) {
                        clickEmpty(ii, jj, board);
                    }
                }
            }
        }
        
        private boolean isValid(char[][] board, int i, int j, char c) {
            return 0 <= i && i < board.length 
                    && 0 <= j && j < board[0].length 
                    && board[i][j] == c;
        }
    }
    

Log in to reply
 

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