模板題目:DFS (130. Surrounded Regions)

Tech In Pieces發表於2020-12-17

Given a 2D board containing ‘X’ and ‘O’ (the letter O), capture all regions surrounded by ‘X’.
不太好直觀理解 見下面的例子:
Example:

X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X
也就是說將所有被X包圍的O 都變成X 但是如果O存在於邊界 就不算是被包圍。
refer:
Java DFS + boundary cell turning solution, simple and clean code, commented.

class Solution {
    public void solve(char[][] board) {
        if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) return;
        
        int m = board.length - 1;
        int n = board[0].length - 1;
        //首先我們把邊上的O(以及其所連線的所有的O)全部改成1
        for(int i = 0; i<=m; i++){
            if(board[i][0] == 'O'){
                dfs(board, i, 0);
            }
            if(board[i][n] == 'O'){
                dfs(board, i, n);
            }
        }
        for(int i = 0; i<=n; i++){
            if(board[0][i] == 'O'){
                dfs(board, 0, i);
            }
            if(board[m][i] == 'O'){
                dfs(board, m, i);
            }
        }
//然後再對全域性進行遍歷 將所有的O變成X就行了 因為這個時候所有的鄰接邊界的O都變成1了 然後我們把所有的1都變O就行了
        for(int i = 0; i<=m; i++){
            for(int j = 0; j<=n; j++){
                if(board[i][j] == 'O'){
                    board[i][j] = 'X';
                }
                if(board[i][j] == '1'){
                    board[i][j] = 'O';
                }
            }
        }
        
    }
    
    public void dfs(char[][] board, int i, int j){
        if(i<0 || j<0 || i>= board.length || j>= board[0].length || board[i][j] != 'O'){ //之前一直沒通過是因為這兒
            return;
        }
        board[i][j] = '1';
        dfs(board, i, j-1);
        dfs(board, i, j+1);
        dfs(board, i-1, j);
        dfs(board, i+1, j);
    }
}

相關文章