Java DFS Solution, easy and straightforward


  • 0
    L
    public char[][] updateBoard(char[][] board, int[] click) {
        int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0};
        int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1};
        update(board, click[0], click[1], dx, dy);
        return board;
    }
    
    private void update(char[][] board, int i, int j, int[] dx, int[] dy) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] == 'B') return;
        
        if (board[i][j] == 'M') {
            board[i][j] = 'X';
            return;
        }
        
        int count = countAdjacentMines(board, i, j, dx, dy);
        if (count != 0) {
            board[i][j] = (char) (count + '0');
            return;
        }
        
        board[i][j] = 'B';
        for (int k = 0; k < 8; k++) {
            update(board, i + dx[k], j + dy[k], dx, dy);
        }
    }
    
    private int countAdjacentMines(char[][] board, int i, int j, int[] dx, int[] dy) {
        int count = 0;
        for (int k = 0; k < 8; k++) {
            int row = i + dx[k], col = j + dy[k];
            if (row >= 0 && row < board.length && col >= 0 && col < board[0].length && board[row][col] == 'M') count++;
        }
        return count;
    }
    

Log in to reply
 

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