LeetCode130. 被围绕的区域

/*
 * 给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
 *  
 * 
 * 示例 1:
 * 
 * 
 * 输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
 * 输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
 * 解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
 * 示例 2:
 * 
 * 输入:board = [["X"]]
 * 输出:[["X"]]
 *  
 * 
 * 提示:
 * 
 * m == board.length
 * n == board[i].length
 * 1 <= m, n <= 200
 * board[i][j] 为 'X' 或 'O'
 * 
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/surrounded-regions
 * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 */
class Solution {
public:
    void solve(vector<vector<char>> &board)
    {
        row = board.size();
        col = board.front().size();
        // For edge point, DFS.
        for (auto i = 0; i < row; i++) {
            for (auto j = 0; j < col; j++) {
                if (i == 0 || i == (row - 1) || j == 0 || j == (col - 1)) {
                    DFS(board, i, j);
                }
            }
        }

        for (auto &vec : board) {
            for (auto &c : vec) {
                if (c == 'O' || c == 'Y') {
                    c = 'X';
                } else if (c == 'P') {
                    c = 'O';
                }
            }
        }
    }

private:
    int row{};
    int col{};
    void DFS(vector<vector<char>> &board, int row, int col)
    {
        // invalid parameters;
        if (!(row >= 0 && row < this->row && col >= 0 && col < this->col)) {
            return;
        }

        // visited. 'Y' means visited 'X', 'P' means visited 'O'.
        if (board[row][col] == 'Y' or board[row][col] == 'P') {
            return;
        }

        // 'X'
        if (board[row][col] == 'X') {
            board[row][col] = 'Y';
            return;
        }

        // 'O'
        board[row][col] = 'P';
        static vector<pair<int, int>> direct{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (const auto &item : direct) {
            DFS(board, row + item.first, col + item.second);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值