Java DFS


  • 0
    Y
    public class Solution {
        public char[][] updateBoard(char[][] board, int[] click) {
            int a = click[0], b = click[1];
            switch(board[a][b]) {
                case 'M':
                    board[a][b] = 'X';
                    break;
                case 'E':
                    mark(board, click);
                    break;
            }
            return board;
        }
        int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
        int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
        private void mark(char[][] board, int[] click) {
            int m = board.length, n = board[0].length;
            int x = click[0], y = click[1];
            if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'E') return;
            int cnt = getMines(board, x, y);
            if (cnt > 0) board[x][y] = (char) ('0' + cnt);
            else {
                board[x][y] = 'B';
                for (int k = 0; k < dx.length; k ++) {
                    int ii = x + dx[k], jj = y + dy[k];
                    mark(board, new int[] {ii, jj});
                }
            }
        }
        
        private int getMines(char[][] board, int i, int j) {
            int cnt = 0;
            for (int k = 0; k < dx.length; k ++) {
                int ii = i + dx[k], jj = j + dy[k];
                if (ii >= 0 && ii < board.length && jj >= 0 && jj < board[0].length && board[ii][jj] == 'M') cnt ++;
            }
            return cnt;
        }
    }
    

Log in to reply
 

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