dfs, 由于和边界值上的"O"相连的都不能被修改,先对边界值相邻的"O"进行状态调整,再修改符合条件的 "O" 的值
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param board char字符型二维数组
# @return char字符型二维数组
#
class Solution:
def surroundedArea(self , board: List[List[str]]) -> List[List[str]]:
# write code here
m, n = len(board), len(board[0])
dirs = [(0, -1), (-1, 0), (0, 1), (1, 0)]
def dfs(x, y, board):
board[x][y] = "G"
for i, j in dirs:
xi, yi = x + i, y + j
if 0 <= xi < m and 0 <= yi < n and board[xi][yi] == "O":
dfs(xi, yi, board)
for i in range(n):
if board[0][i] == "O":
dfs(0, i, board)
if board[m - 1][i] == "O":
dfs(m - 1, i, board)
for i in range(m):
if board[i][0] == "O":
dfs(i, 0, board)
if board[i][n - 1] == "O":
dfs(i, n - 1, board)
for i in range(m):
for j in range(n):
if board[i][j] == "O":
board[i][j] = "X"
for i in range(m):
for j in range(n):
if board[i][j] == "G":
board[i][j] = "O"
return board