[leetcode] 130.Surrounded Regions

题目:
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’,找出所有被X包围的范围,将里面的O改成O。
思路:
这个题目有点像下围棋的感觉,我们不妨可以反过来思考这个问题。题目让找出被X包围的O并将其改为X。我们不妨找出那些不能被修改的O,不能被包围的部分是与四个边上的O相邻的O,相邻的意思是这两个点的位置处于上下位置或者左右位置。如果不能从四个边到达的O一定是被X包围起来的,所以我们的目标就变成了找出所有与四个边上的O相邻的所有 O,然后把它们标记为‘+’这类符号,把剩下的O全部改成X即可。
代码如下:
采用广度优先搜索,把所有的四个边上的O的位置找出来,并把这些O改为+,接下来通过广度优先搜索的方法找出其他的O。

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int row = board.size();
        if(row == 0)return;
        int col = board[0].size();
        if(col == 0)return;
        queue<pair<int,int>> OIndex;
        for(auto i = 0; i < col; i++) {
            if(board[0][i] == 'O') {
                OIndex.push(make_pair(0, i));
                board[0][i] = '+';
            }
            if(board[row - 1][i] == 'O') {
                OIndex.push(make_pair(row-1, i));
                board[row - 1][i] = '+';
            }
        }

        for(auto i = 0; i < row; i++) {
            if(board[i][0] == 'O') {
                OIndex.push(make_pair(i, 0));
                board[i][0] = '+';
            }
            if(board[i][col - 1] == 'O') {
                OIndex.push(make_pair(i, col - 1));
                board[i][col - 1] = '+';
            }
        }

        while(!OIndex.empty()) {
            pair<int,int> index = OIndex.front();
            OIndex.pop();
            if(index.first != 0 && board[index.first - 1][index.second] == 'O') {
                board[index.first - 1][index.second] = '+';
                OIndex.push(make_pair(index.first - 1, index.second));
            }
            if(index.first != row - 1 && board[index.first + 1][index.second] == 'O') {
                board[index.first + 1][index.second] = '+';
                OIndex.push(make_pair(index.first + 1, index.second));
            }
            if(index.second != 0 && board[index.first][index.second - 1] == 'O') {
                board[index.first][index.second - 1] = '+';
                OIndex.push(make_pair(index.first, index.second - 1));
            }
            if(index.second != col - 1 && board[index.first][index.second + 1] == 'O') {
                board[index.first][index.second + 1] = '+';
                OIndex.push(make_pair(index.first, index.second + 1));
            }
        }
        for(auto i = 0; i < row; i++)
            for(auto j = 0; j < col; j++){
                if(board[i][j] == 'O')board[i][j] = 'X';
                else if(board[i][j] == '+')board[i][j] = 'O';
            }
    }
};
阅读更多
文章标签: 广度优先搜索
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode] 130.Surrounded Regions

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭