1. 程式人生 > 實用技巧 >leetcode——130.被圍繞的區域

leetcode——130.被圍繞的區域

做出來了,但是時間用的比較長。

用了遞迴。

public void solve(char[][] board) {
        int m = board.length;
        if(m == 0){
            return;
        }
        int n = board[0].length;
        if(n == 0){
            return;
        }
        boolean[][] visited = new boolean[m][n];  //標記是否被訪問過
        List<List<Integer>> list = new
ArrayList<>(); //存放相鄰的'O'字元的位置 for(int i = 0;i<m;i++){ for(int j = 0;j<n;j++){ if(!visited[i][j]) { if (board[i][j] == 'X') { visited[i][j] = true; } else { boolean b = true
; if(find(i,j,m,n,board,visited,list,b)){ //被包圍 for (List<Integer> l : list) { board[l.get(0)][l.get(1)] = 'X'; } } list.clear(); } } } } }
private boolean find(int i, int j, int m, int n, char[][] board, boolean[][] visited, List<List<Integer>> list,boolean b) { if(i<0 || i>=m || j<0 || j>= n){ return b; } if(!visited[i][j] ) { if (board[i][j] == 'O') { if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { //位置(i,j)處的字元是O //如何判斷邊界 b = false; } List<Integer> local = new ArrayList<>(); local.add(i); local.add(j); list.add(local); //先將起點座標存入 visited[i][j] = true; return find(i, j - 1, m, n, board, visited, list, b) & find(i, j + 1, m, n, board, visited, list, b) & find(i + 1, j, m, n, board, visited, list, b) & find(i - 1, j, m, n, board, visited, list, b); }else{ visited[i][j] = true; } } return b; }

別人的題解,比我的優化多了

public void solve(char[][] board) {
        if(board.length==0) return;
        int m =board.length,n =board[0].length;
        boolean[][] visit=new boolean[m][n];
        for (int i = 0; i < n; i++) {
            if(board[0][i]=='O'){
                solveHelp(board,0,i,visit);
            }
            if(board[m-1][i]=='O'){
                solveHelp(board,m-1,i,visit);
            }
        }
        for (int i = 0; i < m; i++) {
            if(board[i][0]=='O'){
                solveHelp(board,i,0,visit);
            }
            if(board[i][n-1]=='O'){
                solveHelp(board,i,n-1,visit);
            }
        }
        for (int i = 0; i <m ; i++) {
            for (int j = 0; j <n ; j++) {
                if(board[i][j]=='T') board[i][j]='O';
                else board[i][j]='X';
            }
        }

    }
    void solveHelp(char[][] board,int i,int j,boolean[][] visit){
        if(visit[i][j]) return;
        visit[i][j]=true;
        if(board[i][j]=='O') board[i][j]='T';
        if(i>0&&board[i-1][j]=='O'){
            solveHelp(board,i-1,j,visit);
        }
        if(i<board.length-1&&board[i+1][j]=='O'){
            solveHelp(board,i+1,j,visit);
        }
        if(j>0&&board[i][j-1]=='O'){
            solveHelp(board,i,j-1,visit);
        }
        if(j<board[0].length-1&&board[i][j+1]=='O'){
            solveHelp(board,i,j+1,visit);
        }
    }

——2020.8.3