📅  最后修改于: 2023-12-03 15:11:40.526000             🧑  作者: Mango
给定一个二维矩阵,其中包含"O"和"X"两种字符。将被"X"包围的"O"替换成"X"。
被"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
def solve(board):
if not board:
return []
m, n = len(board), len(board[0])
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 j in range(n):
dfs(0, j)
dfs(m-1, j)
# 遍历第一列和最后一列
for i in range(m):
dfs(i, 0)
dfs(i, n-1)
# 用"#"替换掉矩阵中的"O"
for i in range(m):
for j in range(n):
if board[i][j] == "O":
board[i][j] = "X"
# 将所有的"#"替换成"O"
for i in range(m):
for j in range(n):
if board[i][j] == "#":
board[i][j] = "O"
return board