python 给出一个由‘O’和‘X’组成的矩阵,在矩阵中的所有‘X’所在的行、列都需要变成‘O’。 如果在矩阵边界上的‘O’所在的行、列被‘X’包围,则这些‘O’也需要变成‘X’。 样例: 输入: [ ["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"] ]
时间: 2023-07-07 19:39:01 浏览: 134
可以使用DFS或BFS来解决此问题。下面是使用DFS的Python代码:
```python
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return
m, n = len(board), len(board[0])
# DFS遍历边界
def dfs(i, j):
if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != 'O':
return
board[i][j] = '#'
dfs(i-1, j) # 上
dfs(i+1, j) # 下
dfs(i, j-1) # 左
dfs(i, j+1) # 右
for i in range(m):
dfs(i, 0)
dfs(i, n-1)
for j in range(n):
dfs(0, j)
dfs(m-1, j)
# 标记'O'和'X'
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
elif board[i][j] == '#':
board[i][j] = 'O'
```
注意,这里使用了Python的列表和递归函数,需要对输入进行检查以避免出现越界等错误。
阅读全文