130.被围绕的区域

【LetMeFly】130.被围绕的区域 - BFS:标记没有被围绕的区域

力扣题目链接:https://leetcode.cn/problems/surrounded-regions/

给你一个 m x n 的矩阵 board ,由若干字符 'X''O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O''X' 填充。

 

示例 1:

输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

示例 2:

输入:board = [["X"]]
输出:[["X"]]

 

提示:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j]'X''O'

方法一:BFS:标记没有被围绕的区域

这道题是让“被X包围的O”变成X

不如换个思考角度:

我们可以很容易地求出“没有被X包围的O”(从四条边开始搜素即可)

然后把“没有被X包围的O”标记一下,之后再遍历一遍原始矩阵,把所有没有被标记过的O变成X即可

  • 时间复杂度$O(nm)$,其中$board$的size为$n\times m$
  • 空间复杂度$O(nm)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
typedef pair<int, int> pii;
const int directions[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};

class Solution {
private:
vector<vector<bool>> isnot; // true:不是被包围的O false:(还)未被认定为“不是被包围的O”
int n, m;

void extend(int x, int y, vector<vector<char>>& a) {
if (a[x][y] == 'O' && !isnot[x][y]) {
queue<pii> q;
isnot[x][y] = true;
q.push({x, y});
while (q.size()) {
auto[x, y] = q.front();
q.pop();
for (int d = 0; d < 4; d++) {
int tx = x + directions[d][0];
int ty = y + directions[d][1];
if (tx >=0 && tx < n && ty >= 0 && ty < m) {
if (a[tx][ty] == 'O' && !isnot[tx][ty]) {
isnot[tx][ty] = true;
q.push({tx, ty});
}
}
}
}
}
}
public:
void solve(vector<vector<char>>& board) {
n = board.size(), m = board[0].size();
isnot = vector<vector<bool>>(n, vector<bool>(m, false));
for (int i = 0; i < n; i++) {
extend(i, 0, board);
extend(i, m - 1, board);
}
for (int j = 0; j < m; j++) {
extend(0, j, board);
extend(n - 1, j, board);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 'O' && !isnot[i][j]) {
board[i][j] = 'X';
}
}
}
}
};

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125929415


130.被围绕的区域
https://blog.letmefly.xyz/2022/07/22/LeetCode 0130.被围绕的区域/
作者
Tisfy
发布于
2022年7月22日
许可协议