【LeetCode】130. Surrounded Regions

题目:
Given a 2D board containing ‘X’ and ‘O’ (the letter 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

分析:
这道题要求将所有被包围的’O’区域变成’X’.我的思路是使用BFS算法找到所有不被X包围的’O’区域,即在边界位置的’O’区域,并进行标记。在BFS结束后将没有被标记过的’O’全部变成’X’。

代码:

class Solution {
public:
    void solve(vector<vector<char>>& board) {

        for(int i =0;i<board.size();i++)
        {
            for(int j = 0;j<board[0].size();j++)
            {
                if(board[i][j] == 'O'&&(i == 0||j==0||i==board.size()-1||j == board[0].size()-1))
                {
                    BFS(board,i,j);
                }
            }
        }
        for(int i = 0;i<board.size();i++)
        {
            for(int j = 0;j<board[0].size();j++)
            {
                if(board[i][j] == 'O')
                board[i][j] = 'X';
                if(board[i][j] == 'A')
                board[i][j] = 'O';
            }
        }
    }

    void BFS(vector<vector<char>>& board,int i,int j)
    {
        queue<pair<int,int> > q;
        board[i][j] = 'A';
        q.push(pair<int,int>(i,j));
        while(!q.empty())
        {
            int n = q.front().first;
            int m = q.front().second;
            q.pop();
            if(n>0&&board[n-1][m] == 'O')
            {
                q.push(pair<int,int>(n-1,m));
                board[n-1][m]='A';
            }
            if(n<board.size()-1&&board[n+1][m]=='O')
            {
                q.push(pair<int,int>(n+1,m));
                board[n+1][m]='A';
            }
            if(m>0&&board[n][m-1]=='O')
            {
                q.push(pair<int,int>(n,m-1));
                board[n][m-1]='A';
            }
            if(m<board[0].size()-1&&board[n][m+1]=='O')
            {
                q.push(pair<int,int>(n,m+1));
                board[n][m+1]='A';
            }          
        }

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值