Easy JAVA DFS solution


  • 0
    H
    class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            if (board.length == 0) return board;
            int x = click[0], y = click[1];
            if (board[x][y] == 'M') {
                board[x][y] = 'X';
                return board;
            }
            dfs(board, x, y);
            return board;
        }
    
        private void dfs(char[][] board, int x, int y) {
            if (x < 0 || x > board.length - 1 || y < 0 || y > board[0].length - 1 || board[x][y] != 'E') return;
            int count = 0;
            for (int i = -1; i < 2; i++) {
                for (int j = -1; j < 2; j++) {
                    if (x + i < 0 || x + i > board.length - 1 || y + j < 0 || y + j > board[0].length - 1) continue;
                    if (board[x + i][y + j] == 'M' || board[x + i][y + j] == 'X') count++;
                }
            }
            if (count == 0) {
                board[x][y] = 'B';
                for (int i = -1; i < 2; i++) {
                    for (int j = -1; j < 2; j++) {
                        dfs(board, x + i, y + j);
                    }
                }
            }
            else board[x][y] = (char)('0' + count);       
        }
    }
    

Log in to reply
 

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