leetcode(130)被围绕的区域

被围绕的区域

解题思路:递归+深度优先遍历+逆向思维

class Solution {
    public void solve(char[][] board) {
        if(board.length==0||board[0].length==0){
            return;
        }
        int xlen = board.length;
        int ylen = board[0].length;
        boolean[][] flags = new boolean[xlen][ylen]; 
        int i = 0;
        for(int j=0;j<ylen;j++) {
            if(board[i][j]=='O') {
                dfs(board,flags,xlen,ylen,i,j);
            }
        }
        i = xlen-1;
        for(int j=0;j<ylen;j++) {
            if(board[i][j]=='O') {
                dfs(board,flags,xlen,ylen,i,j);
            }
        }
        i = 0;
        for(int j=1;j<xlen-1;j++) {
            if(board[j][i]=='O') {
                dfs(board,flags,xlen,ylen,j,i);
            }
        }
        i = ylen-1;
        for(int j=1;j<xlen-1;j++) {
            if(board[j][i]=='O') {
                dfs(board,flags,xlen,ylen,j,i);
            }
        }
        for(i=1;i<xlen-1;i++) {
            for(int j=1;j<ylen-1;j++) {
                if(flags[i][j]==false&&board[i][j]=='O') {
                    board[i][j]='X';
                }
            }
        }
    }
    public static void dfs(char[][] board,boolean[][] flags,int xlen,int ylen,int x,int y ) {
        if(x<0||y<0||x==xlen||y==ylen) {
            return;
        }
        if(flags[x][y]==true) {
            return;
        }
        if(board[x][y]=='X') {
            return;
        }
        if(board[x][y]=='O') {
            flags[x][y]=true;
            dfs(board,flags,xlen,ylen,x+1,y);
            dfs(board,flags,xlen,ylen,x-1,y);
            dfs(board,flags,xlen,ylen,x,y+1);
            dfs(board,flags,xlen,ylen,x,y-1);
        }
    }
}

 

posted @ 2019-07-03 17:57  海平面下的我们  阅读(188)  评论(0编辑  收藏  举报