扫雷问题
自己先做出来了流程图,根据流程图写出来了大部分的结构,但是总是有问题,有一个计数变量cnt要么未定义,要么就是引用前赋值局部变量的问题。查阅了好多无法解决。无奈之下只能换思路
dfs优秀解法
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
direction = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
return board
self.m,self.n = len(board), len(board[0])
def check(i, j):
cnt = 0
for x,y in direction:
x, y = x + i, y + j
if 0 <= x < self.m and 0 <= y < self.n and board[x][y]=='M':
cnt += 1
return cnt
def dfs(i, j):
cnt = check(i, j)
if not cnt:
board[i][j] = 'B'
for x, y in direction:
x, y = x + i, y + j
if 0 <= x < self.m and 0 <= y < self.n and board[x][y]=='E': dfs(x, y)
else: board[i][j] = str(cnt)
dfs(click[0],click[1])
return board
思路上没有太多变动,但是需要学习人家的细节的点很多。
1、用一个元组把顺序搜索的元素的角标的偏移量保存,这样可以将搜索过程做成循环迭代,不至于每一个自己修改(自己做的时候是手动添加的)。重点是这样无需将判断改成函数了,更简洁了。
for x, y in direction:
x, y = x + i, y + j
2、根据情况决定是否需要单开一张列表去修改和保存结果。在此处因为只需要对E进行搜索,而被搜索后的元素必然不是E,所以无需因为标记而单开一张列表