leetcode-130.被围绕的区域

leetcode-130.被围绕的区域_第1张图片

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.size() == 0) return;
        int row = board.size();
        int col = board[0].size();
        // 左右边界
        for(int i = 0; i < row; i++) {
            dfs(board, i, 0);
            dfs(board, i, col - 1);
        }
        // 上下边界
        for(int j = 0; j < col; j++) {
            dfs(board, 0, j);
            dfs(board, row - 1, j);
        }
        for(int i = 0; i < board.size(); i++) {
            for(int j = 0; j < board[0].size(); j++) {
                if(board[i][j] == '1') {
                    board[i][j] = 'O';
                }
                else {
                    board[i][j] = 'X';
                }
            }
        }
    }
    void dfs(vector<vector<char>>& board, int row, int col) {
    //只有边界有 'O'的才有必要往下进行深度遍历
        if(row >= 0 && row < board.size() && col >= 0 && col < board[0].size() && board[row][col] == 'O') {
            board[row][col] = '1';
            dfs(board, row + 1, col);
            dfs(board, row - 1, col);
            dfs(board, row, col - 1);
            dfs(board, row, col + 1);
        }
    }
};

你可能感兴趣的:(leetcode)