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 |
|
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125929415
130.被围绕的区域
https://blog.letmefly.xyz/2022/07/22/LeetCode 0130.被围绕的区域/