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;
}
}