1. 程式人生 > >LetCode 130. 被圍繞的區域

LetCode 130. 被圍繞的區域

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.size() <= 0 || board[0].size() <= 0)
            return;
        int row = board.size();
        int col = board[0].size();
        // 第一列和最後一列進行DFS,將與邊界O相鄰的O全部標記為*
        for (int i = 0; i < row; ++i){
            if (board[i][0] == 'O')
                search(board, i, 0);
            if (board[i][col - 1] == 'O')
                search(board, i, col - 1);
        }
        for (int i = 0; i < col; ++i){
            if (board[0][i] == 'O')
                search(board, 0 , i);
            if (board[row - 1][i] == 'O')
                search(board, row - 1, i);
        }
        // 最後,標記為‘*’的表示,這塊O連通圖為沒有被包圍的,還原為'O',仍然為‘O’的表示被X包圍了,要改成‘X’
        for (int i = 0; i < row; ++i)
            for (int j = 0; j < col; ++j)
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                else if (board[i][j] == '*')
                    board[i][j] = 'O';
    }
    
    void search(vector<vector<char>>& board, int row, int col){
        if (row < 0 || col < 0 || row >= board.size() || col >= board[0].size())
            return;
        if (board[row][col] != 'O')
            return;
        board[row][col] = '*';
        search(board , row + 1, col);
        search(board , row - 1, col);
        search(board , row , col + 1);
        search(board , row , col - 1);
    }
};

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();