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


This question is to use BFS. But, instead of using queue, we should use vector.... to save the walked positions.


#include <vector>
#include <string>
#include <iostream>

using namespace std;

// BFS
bool checkSurroundRegions(vector< vector<char> >& board, int i, int j, vector< vector<bool> >& visited) {
    visited[i][j] = true;
    struct direction {
        int x;
        int y;
    };
    bool surrounded = true;
    vector<direction> positions;
    positions.push_back({i, j});
    int idx = 0;
    while(idx < positions.size()) {
        const auto curr = positions[idx++];
        if(curr.x == 0 || curr.x == board.size() - 1 || curr.y == 0 || curr.y == board[curr.x].size()- 1) {
            surrounded = false;
        } else {
            vector< vector<int> > dir = {
                { 0,  1},
                { 0, -1},
                { 1,  0},
                {-1,  0}};
            for(int i = 0; i < dir.size(); ++i) {
                direction nextPos;
                nextPos.x = curr.x + dir[i][0];
                nextPos.y = curr.y + dir[i][1];
                if(board[nextPos.x][nextPos.y] == 'O' && !visited[nextPos.x][nextPos.y]) {
                    visited[nextPos.x][nextPos.y] = true;
                    positions.push_back(nextPos);
                }
            }
        }
    }
    if(surrounded) {
        for(int i = 0;  i < positions.size(); ++i) {
            board[positions[i].x][positions[i].y] = 'X';
        }
    }
}

void solve(vector< vector<char> >& board) {
    if(board.size() == 0) return;
    if(board[0].size() == 0) return;
    int m = board.size();
    int n = board[0].size();
    vector< vector<bool> > visited(m, vector<bool>(n, false));
    for(int i = 1; i < m; ++i) {
        for(int j = 1; j < n; ++j) {
            if(board[i][j] == 'O' && !visited[i][j]) {
                checkSurroundRegions(board, i, j, visited);
            }
        }
    }
    return;
}

int main(void) {
    vector< vector<char> > board{
        {'X', 'X', 'X', 'X'},
        {'X', 'X', 'O', 'X'},
        {'X', 'O', 'O', 'X'},
        {'X', 'O', 'X', 'X'}};
    solve(board);

    for(int i = 0; i < board.size(); ++i) {
        for(int j = 0; j < board[0].size(); ++j) {
            cout << board[i][j] << ',';
        }
        cout << endl;
    }
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值