130. Surrounded Regions

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

For 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

一刷:

  1. 在4條邊上,如果有元素為'O', 則轉(zhuǎn)為'1', 并且與它相臨的'O'都轉(zhuǎn)為'1'
  2. 將其他的'O'都轉(zhuǎn)為'X'
  3. 將'1'都轉(zhuǎn)為'O'
public class Solution {
    public void solve(char[][] board) {
        int row = board.length;
        if(row==0) return;
        int col = board[0].length;
        
        
        //flip the 0 in the edge and adjacent area to 1
        for(int i=0; i<row; i++){
            check(board, i, 0, row, col);//edge
            if(col>1) check(board, i, col-1, row, col);//edge
        }
        for(int j=0; j<col; j++){
            check(board, 0, j, row, col);//edge
            if(row>1) check(board, row-1, j, row, col);//edge
        }
        
        
        //flip all other 0 to x
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(board[i][j] == 'O') board[i][j] = 'X';
            }
        }
        
        //flip all 1 to 0
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(board[i][j] == '1') board[i][j] = 'O';
            }
        }
    }
    
    private void check(char[][] board, int i, int j, int row, int col){
        //flip the 0 in the edge to 1
        if(board[i][j] == 'O'){
            board[i][j] = '1';
            if(i>1) check(board, i-1, j, row, col);
            if(j>1) check(board, i, j-1, row, col);
            if(i+1<row) check(board, i+1, j, row, col);
            if(j+1<col) check(board, i, j+1, row, col);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容