广度优先搜索|130. 被围绕的区域,529. 扫雷游戏
被围绕的区域
也是得倒流,做法和深度优先其实差不多。
python
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def bfs(queue,board):
while queue:
x, y = queue.popleft()
for k1,k2 in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=k1<m and 0<=k2<n and board[k1][k2] == 'O':
queue.append([k1,k2])
board[k1][k2] = 'A'
return board
m = len(board)
n = len(board[0])
queue = deque()
for i in range(m):
if board[i][0] == 'O':
queue.append([i,0])
board[i][0] = 'A'
if board[i][n-1] == 'O':
queue.append([i,n-1])
board[i][n-1] = 'A'
for j in range(n):
if board[0][j] == 'O':
queue.append([0,j])
board[0][j] = 'A'
if board[m-1][j] == 'O':
queue.append([m-1,j])
board[m-1][j] = 'A'
board = bfs(queue,board)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == 'A':
board[i][j] = 'O'
扫雷游戏
这里没写visit数列,所以在列队走到那里之后还是要改成B防止他反复进列队。
python
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
#direc = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]]
m = len(board)
n = len(board[0])
def empty(i,j):
boom = 0
for k1,k2 in [[i+1,j],[i-1,j],[i,j+1],[i,j-1],[i+1,j+1],[i-1,j+1],[i-1,j-1],[i+1,j-1]]:
#x = i+k1
#y = j+k2
if (0<=k1<m and 0<=k2<n) and board[k1][k2] == 'M':
boom += 1
return boom
queue = deque()
queue.append([click[0],click[1]])
while queue:
x,y = queue.popleft()
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
return board
num_b = empty(x,y)
if not num_b:
board[x][y] = 'B'
else:
board[x][y] = str(num_b)
continue
for k1,k2 in [[x+1,y],[x-1,y],[x,y+1],[x,y-1],[x+1,y+1],[x-1,y+1],[x-1,y-1],[x+1,y-1]]:
if 0<=k1<m and 0<=k2<n and board[k1][k2]=='E':
queue.append([k1,k2])
board[k1][k2] = 'B' #这里改B是因为改了之后这个点就不会重复进队了!
return board