【网格问题】leetcode130.被围绕的区域
作者:互联网
题目:
给你一个 m x n 的矩阵 board ,由若干字符 ‘X’ 和 ‘O’ ,找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。
解答:
方法一:BFS
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
#BFS,从边界的O出发,将与边界O直接或间接相连的O,标记为'A'
directions=[[-1,0],[1,0],[0,-1],[0,1]]
q=deque()
m=len(board)
n=len(board[0])
for i in range(m):
if board[i][0]=='O':
q.append((i,0))
if board[i][n-1]=='O':
q.append((i,n-1))
for j in range(1,n-1):
if board[0][j]=='O':
q.append((0,j))
if board[m-1][j]=='O':
q.append((m-1,j))
def InArea(i,j):
if 0<=i<m and 0<=j<n:
return True
return False
while q:
x,y=q.popleft()
board[x][y]='A'
for dx,dy in directions:
curx,cury=x+dx,y+dy
if InArea(curx,cury) and board[curx][cury]=='O':
q.append((curx,cury))
for i in range(m):
for j in range(n):
#被标记的还原为'O',未被标记的变换为'X'
if board[i][j]=='A':
board[i][j]='O'
elif board[i][j]=='O':
board[i][j]='X'
return board
方法二:DFS
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
#DFS,从边界的O出发,将与边界O直接或间接相连的O,标记为'A'
directions=[[-1,0],[1,0],[0,-1],[0,1]]
m=len(board)
n=len(board[0])
def InArea(i,j):
if 0<=i<m and 0<=j<n:
return True
return False
def dfs(x, y):
if not InArea(x,y) or board[x][y] != 'O':
return
#将当前位置标记为'A'
board[x][y] = "A"
for dx,dy in directions:
dfs(x+dx,y+dy)
#左边界和右边界
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
#上边界和下边界
for j in range(1,n - 1):
dfs(0, j)
dfs(m - 1, j)
#将被标记为A的还原为O,将未被标记的O替换为X
for i in range(m):
for j in range(n):
if board[i][j] == "A":
board[i][j] = "O"
elif board[i][j] == "O":
board[i][j] = "X"
return board
标签:边界,围绕,List,网格,len,leetcode130,def,board,append 来源: https://blog.csdn.net/jqq125/article/details/122838115