LeetCode 130 被围绕的区域
题目链接:LeetCode 130 被围绕的区域
题目大意:
给你一个\(m\times n\)的矩阵\(board\),由若干字符\('X'\)和\('O'\),找到所有被\('X'\)围绕的区域,并将这些区域里所有的\('O'\)用\('X'\)填充。
题解:
很明显只有边缘的\('O'\)以及直接或间接与这些\('O'\)相连的\('O'\)不会被填充。
所以从边缘的\('O'\)向内搜索将所有相连的\('O'\)标记,最后将矩阵中未标记的\('O'\)填充。
class Solution {
private:
static constexpr int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
void solve(vector<vector<char>>& board) {
int n = board.size(), m = board[0].size();
queue <pair<int, int>> q;
for (int i = 0; i < n; ++i) {
if (board[i][0] == 'O') {
q.emplace(i, 0);
}
if (board[i][m - 1] == 'O') {
q.emplace(i, m - 1);
}
}
for (int i = 1; i < m - 1; ++i) {
if (board[0][i] == 'O') {
q.emplace(0, i);
}
if (board[n - 1][i] == 'O') {
q.emplace(n - 1, i);
}
}
while (!q.empty()) {
auto& [x, y] = q.front();
if (x >= 0 && y >= 0 && x < n && y < m && board[x][y] == 'O') {
board[x][y] = '#';
for (int i = 0; i < 4; ++i) {
q.emplace(x + dir[i][0], y + dir[i][1]);
}
}
q.pop();
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
}
};