当前位置:网站首页>130. 被围绕的区域

130. 被围绕的区域

2022-07-07 23:18:00 anieoo

原题链接:130. 被围绕的区域

 

solution:

        dfs

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int m = board.size(),n = board[0].size();
        for(int i = 0;i < m;i++) {
            dfs(board, i, 0);
            dfs(board, i, n - 1);
        }

        for(int j = 0;j < n;j++) {
            dfs(board, 0, j);
            dfs(board, m - 1, j);
        }

        for(int i = 0;i < m;i++)
            for(int j = 0;j < n;j++) {
                if(board[i][j] == '#') board[i][j] = 'O';
                else if(board[i][j] == 'O') board[i][j] = 'X';
            }
    }


    //从外边界dfs,将每一个可以延伸的O变为#,在进行m*n遍历,将剩余的O变为X
    void dfs(vector<vector<char>> &board, int x,int y) {
        if(x < 0 || x == board.size() || y < 0 || y == board[0].size() || board[x][y] != 'O') return;
        board[x][y] = '#';
        dfs(board, x + 1, y);
        dfs(board, x, y + 1);
        dfs(board, x - 1, y);
        dfs(board, x, y - 1);
    }
};
原网站

版权声明
本文为[anieoo]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42174306/article/details/125667302