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

从四周的O作为入口进行广度优先遍历或者DFS,遍历过的点都做标记,四周都做一遍,之后矩阵中为O并且没有被访问的元素变成X即可.

class Solution {
public:
int movx[4] = { 0, 0, 1, -1 };
int movy[4] = { 1, -1, 0, 0 };
struct position{
    int x;
    int y;
    position(int x1, int y1) :x(x1), y(y1){};

};
void myfind(vector<vector<char>> &board, vector<vector<bool>>& visit, int x, int y)
{
    visit[x][y] = 1;
    int rows = board.size();
    if (rows <= 2)
        return;
    int cols = board[0].size();
    if (cols <= 2)
        return;
    queue<position> que;
    position root(x, y);
    que.push(root);
    while (!que.empty())
    {
        position temp = que.front();
        que.pop();
        for (int i = 0; i<4; ++i)
        {
            int nx = temp.x + movx[i];
            int ny = temp.y + movy[i];
            if (nx >= 0 && nx<rows&&ny >= 0 && ny<cols&&visit[nx][ny] == 0 && board[nx][ny] == 'O')
            {
                que.push(position(nx, ny));
                visit[nx][ny] = 1;
            }
        }

    }
}
void solve(vector<vector<char>> &board) {
    int rows = board.size();
    if (rows <= 2)
        return;
    int cols = board[0].size();
    if (cols <= 2)
        return;
    vector<vector<bool>> visit(rows, vector<bool>(cols, 0));
    for (int i = 0; i<cols; ++i)
    {
            if (board[0][i] == 'O'&&visit[0][i] == 0)
        {
            myfind(board, visit, 0, i);
        }
        if (board[rows - 1][i] == 'O'&&visit[rows-1][i] == 0)
        {
            myfind(board, visit, rows - 1, i);
        }
    }
    for (int i = 0; i<rows; ++i)
    {
        if (board[i][0] == 'O'&&visit[i][0] == 0)
        {
            myfind(board, visit, i, 0);
        }
        if (board[i][cols - 1] == 'O'&&visit[i][cols - 1] == 0)
        {
            myfind(board, visit, i, cols - 1);
        }
    }

    for (int i = 0; i<rows; ++i)
    {
        for (int j = 0; j<cols; ++j){
            if (board[i][j] == 'O'&&visit[i][j] == 0)
                board[i][j] = 'X';
        }

    }
}

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值