130 Surrounded Regions [Leetcode]

44 篇文章 0 订阅
1 篇文章 0 订阅

题目内容:

Given a 2D board containing ‘X’ and ‘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

题目分析:
有两种切入点,一种是查找被围起来的区域,将他们标成’X’,另一种是找边界上的’O’,用排除法,剩下的就是被围起来的区域。
这两种方法都可以用BFS实现,我使用了找边界上与’O’连通的区域,将他们存储到一个队列中,然后使用BFS,找到所有的连通点,设置一个特殊的标志’-‘,最后遍历一遍,将所有的’O’改为’X’,将所有的’-‘改为’O’。
代码实现:

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.size() == 0)
            return;

        int row(board.size()), col(board[0].size()), r, c;
        queue<int> index_x, index_y;

        for(int i = 0; i < col; ++i) {
            if(board[0][i] == 'O') {
                index_x.push(0);
                index_y.push(i);
            }
            if(board[row-1][i] == 'O') {
                index_x.push(row-1);
                index_y.push(i);
            }
        }
        for(int i = 1; i < row-1; ++i) {
            if(board[i][0] == 'O') {
                index_x.push(i);
                index_y.push(0);
            }
            if(board[i][col-1] == 'O') {
                index_x.push(i);
                index_y.push(col-1);
            }
        }

        while(!index_x.empty()) {
            r = index_x.front();
            c = index_y.front();
            index_x.pop();
            index_y.pop();
            board[r][c] = '-';

            if(r > 0 && board[r-1][c] == 'O') {
                index_x.push(r-1);
                index_y.push(c);
            }
            if(r < row-1 && board[r+1][c] == 'O') {
                index_x.push(r+1);
                index_y.push(c);
            }
            if(c > 0 && board[r][c-1] == 'O') {
                index_x.push(r);
                index_y.push(c-1);
            }
            if(c < col-1 && board[r][c+1] == 'O') {
                index_x.push(r);
                index_y.push(c+1);
            }
        }

        for(int i = 0; i < row; ++i) {
            for(int j = 0; j < col; ++j) {
                if(board[i][j] == 'O')
                    board[i][j] = 'X';
                if(board[i][j] == '-')
                    board[i][j] = 'O';
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值