Java DFS


  • 0
    public char[][] updateBoard(char[][] board, int[] click) {
        if(board[click[0]][click[1]] == 'M') {
            board[click[0]][click[1]] = 'X';
            return board;
        }
        dfs(board, click[0], click[1]);
        return board;
    }
    public void dfs(char[][]b, int x, int y) {
        if(b[x][y] != 'E') return;
        int mines = getSurroundingMines(b, x, y);
        if(mines > 0) {
            b[x][y] = Character.forDigit(mines,10);
            return;
        }
        b[x][y] = 'B';
        dfs(b, x, y, new int[]{0,1,0,-1}); //top-down-left-right
        dfs(b, x, y, new int[]{1,-1,-1,1}); //Corners
    }
    public void dfs(char[][]b, int x, int y, int[] dirs) {
        for(int i = 0; i < dirs.length; i++) {
            int m = dirs[i] + x;
            int n = dirs[(i+1)%dirs.length] + y;
            if(m >= 0 && m < b.length && n >= 0 && n < b[m].length) {
                dfs(b, m, n);
            }
        }
    }  
    public int getSurroundingMines(char[][] b, int m, int n) {
        return check(b, m, n, new int[]{0, 1, 0, -1})
                + check(b, m, n, new int[]{1, -1, -1, 1});
    }
    
    public int check(char[][] b, int m, int n, int[] dirs) {
        int mines = 0;
        for (int i = 0; i < dirs.length; i++) {
            int x = dirs[i] + m;
            int y = dirs[(i + 1) % 4] + n;
            if (x >= 0 && x < b.length && y >= 0 && y < b[x].length 
                && (b[x][y] == 'X' || b[x][y] == 'M')) mines++;
        }
        return mines;
    }

Log in to reply
 

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