1. 程式人生 > >130被圍繞的區域

130被圍繞的區域

from typing import List
# 這道題的思路是從矩陣的四周開始尋找,如果這個字元為O,就向上下左右遞迴,
# 先將找到的O轉化為其他字元,最後將沒有找到的O轉化為X,將找到的O不變
class Solution:
def solve(self, board: List[List[str]]) -> None:
# 如果列表為空或者列表中為空,返回空
if not board or not board[0] :return
# 定義行和列
row,col = len(board),len(board[0])
# 定義遞迴函式
def dfs(index1, index2):
# 首先將進來的轉化為其他字元
board[index1][index2] = "B"
# 然後上下左右遞迴
for x, y in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
# 注意這裡不能直接在index1上邊相加減
i = index1 + x
j = index2 + y
# 注意這裡一定是從1開始的,否則就是錯誤的。
if 1 <= i < row and 1 <= j < col and board[i][j] == "O":
dfs(i,j)
# 尋找第一列和最後一列
for i in range(row):
if board[i][0] == "O":
dfs(i,0)
if board[i][col - 1] == "O":
dfs(i,col - 1)
# 尋找第一行和最後一行
for i in range(col):
if board[0][i] == "O":
dfs(0,i)
if board[row - 1][i] == "O":
dfs(row - 1,i)
# 將字元恢復原位。
for i in range(row):
for j in range(col):
if board[i][j] == "O":
board[i][j] = "X"
if board[i][j] == "B":
board[i][j] = "O"


A = Solution()
A.solve([["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]])