from typing import List
# 這道題看了大佬寫的程式碼,經過自己的理解寫出來了。
# 從最外圍的四周找有沒有為O的,如果有的話就進入深搜函式,然後深搜遍歷
# 判斷上下左右的位置是否為O
class Solution:
def solve(self, board: List[List[str]]) -> None:
# 判斷是否為空列表
if not board or not board[0] : return
# 求出列表的有幾行和有幾列
row = len(board)
col = len(board[0])
# 深搜,當邊界為O進行判斷
def dfs(index1,index2):
# 首先將O變成B,之後再變回來。
board[index1][index2] = 'B'
# 遍歷上下左右
for x,y in [(0,1),(0,-1),(1,0),(-1,0)]:
print(x,y)
# 注意這裡不能改變index1和index2的值,因為後邊還要用。
i = index1 + x
j = index2 + y
# 如果當前位置的上下左右不出邊界而且位置上為O就,進行深搜
# 注意這裡邊界上邊不能判斷,
if 1 <= i < row and 1 <= j < col and board[i][j] == "O":
print("111")
dfs(i,j)
# 判斷第一行和最後一行上的邊界值
for index1 in range(col):
if board[0][index1] == "O":
dfs(0,index1)
if board[row - 1][index1] == 'O':
dfs(row - 1,index1)
# 判斷第一列和最後一列的邊界值
for index2 in range(row):
if board[index2][0] == "O":
dfs(index2,0)
if board[index2][col - 1] == 'O':
dfs(index2,col - 1)
# 將O全部改寫成X,將之前寫的B也改寫成O
for index1 in range(row):
for index2 in range(col):
if board[index1][index2] == "O":
board[index1][index2] = "X"
if board[index1][index2] == "B":
board[index1][index2] = 'O'
A = Solution()
print(A.solve([["O","X","X","O","X"],["X","O","O","X","O"],["X","O","X","O","X"],["O","X","O","O","O"],["X","X","O","X","O"]])
)