链接
LeetCode题目:https://leetcode.com/problems/surrounded-regions/
难度:Medium
题目
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.
分析
这题的关键是从每个未搜索过的’O’出发,向上下左右四个方向进行广度优先搜索,如果搜到恰好在边界的’O’,则可以知道当前路径搜索过的’O’没有被’X’包围,即不用转变为’X’。
代码
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
bool out_of_border(int x, int y) {
return x < 0 || x >= height || y < 0 || y >= width;
}
bool on_border(int x, int y) {
return x == 0 || x == height - 1 || y == 0 || y == width - 1;
}
void solve(vector<vector<char>> &board) {
if (board.size() == 0 || board[0].size() == 0)
return;
height = (int) board.size();
width = (int) board[0].size();
vector<vector<bool>> isVisited;
for (int i = 0; i < height; ++i) {
vector<bool> temp;
for (int j = 0; j < width; ++j) {
temp.push_back(false);
}
isVisited.push_back(temp);
}
vector<pair<int, int>> posList;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (board[i][j] != 'O' || isVisited[i][j]) continue;
queue<pair<int, int>> q;
vector<pair<int, int>> tempList;
bool isSurrounded = true;
q.push(pair<int, int>(i, j));
isVisited[i][j] = true;
while (!q.empty()) {
pair<int, int> current_pos = (pair<int, int> &&) q.front();
tempList.push_back(current_pos);
if (on_border(current_pos.first, current_pos.second))
isSurrounded = false;
for (int k = 0; k < 4; k++) {
int next_x = current_pos.first + step[k][0];
int next_y = current_pos.second + step[k][1];
if (out_of_border(next_x, next_y) ||
board[next_x][next_y] != 'O' || isVisited[next_x][next_y])
continue;
isVisited[next_x][next_y] = true;
q.push(pair<int, int>(next_x, next_y));
}
q.pop();
}
if (isSurrounded) {
for (auto pos:tempList) posList.push_back(pos);
}
}
for (auto pos:posList) {
board[pos.first][pos.second] = 'X';
}
}
}
private:
const int step[4][2] = {{-1, 0},
{1, 0},
{0, -1},
{0, 1}};
int height;
int width;
};