classSolution: defsolve(self, board) -> None: """ Do not return anything, modify board in-place instead. """ ifnot board: return
n, m = len(board), len(board[0])
defdfs(x, y): # 如果board[x][y]不是位于矩阵边框,且字符为'x',则返回为空 ifnot0 <= x < n ornot0 <= y < m or board[x][y] != 'O': return # 对于位于矩阵边框,且字符为'0'的元素 board[x][y] = "A" dfs(x + 1, y) dfs(x - 1, y) dfs(x, y + 1) dfs(x, y - 1)
# 检测边框 for i inrange(n): dfs(i, 0) dfs(i, m - 1) # 检测边框 for i inrange(m - 1): dfs(0, i) dfs(n - 1, i)
for i inrange(n): for j inrange(m): if board[i][j] == "A": board[i][j] = "O" elif board[i][j] == "O": board[i][j] = "X"
classSolution: defsolve_BFS(self, board ) -> None: """ Do not return anything, modify board in-place instead. """ ifnot board: return
n, m = len(board), len(board[0]) # 边框有'0'就放入队列 que = collections.deque() for i inrange(n): if board[i][0] == "O": que.append((i, 0)) if board[i][m - 1] == "O": que.append((i, m - 1)) for i inrange(m - 1): if board[0][i] == "O": que.append((0, i)) if board[n - 1][i] == "O": que.append((n - 1, i)) # 队列中的每个元素标记为'A' while que: x, y = que.popleft() board[x][y] = "A" # 检测周围的4个点是否为非边框,且值为'0',如果是,则加入队列 for mx, my in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if0 <= mx < n and0 <= my < m and board[mx][my] == "O": que.append((mx, my))
for i inrange(n): for j inrange(m): if board[i][j] == "A": board[i][j] = "O" elif board[i][j] == "O": board[i][j] = "X"
复杂度分析
时间复杂度:,其中 n 和
分别为矩阵的行数和列数。广度优先搜索过程中,每一个点至多只会被标记一次。