1.所有包含O的边界上的的格子,以及它们的邻居O都不会被包围,暂时地将这些O标记,通过深度优先搜索查找这些O,最后将所有未被标记的O转换为X
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
rows,cols=len(board),len(board[0])
to_expand=[] # 将要被检查的格子构成的栈
for row in range(rows): # 把所有边缘格子加入栈中
to_expand+=[(row,0),(row,cols-1)]
for col in range(1,cols-1):
to_expand+=[(0,col),(rows-1,col)]
def bfs(to_expand):
if (to_expand==None):
return
row,col=to_expand.pop()
if 0<=row<rows and 0<=col<cols and board[row][col]=="O":
board[row][col]="F"
bfs(to_expand.append((row+1,col)))
bfs(to_expand.append((row,col+1)))
bfs(to_expand.append((row-1,col)))
bfs(to_expand.append((row,col-1)))
while to_expand:
bfs(to_expand)
for row in range(rows):
for col in range(cols):
if board[row][col]=="O":
board[row][col]="X"
elif board[row][col]=="F":
board[row][col]="O"
另外一种形式
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
rows,cols=len(board),len(board[0])
to_expand=[] # 将要被检查的格子构成的栈
for row in range(rows): # 把所有边缘格子加入栈中
to_expand+=[(row,0),(row,cols-1)]
for col in range(1,cols-1):
to_expand+=[(0,col),(rows-1,col)]
while to_expand:
row,col=to_expand.pop()
if 0<=row<rows and 0<=col<cols and board[row][col]=="O":
board[row][col]="F"
for dr,dc in [(1,0),(0,1),(-1,0),(0,-1)]:
to_expand.append((row+dr,col+dc))
#把所有的F重新变回O,把被包围的O改为X
for row in range(rows):
for col in range(cols):
if board[row][col]=="O":
board[row][col]="X"
elif board[row][col]=="F":
board[row][col]="O"