题解 | #迷宫问题#
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
def function(board: list) -> list:
n = len(board)
m = len(board[0])
def dfs(i, j, que) -> bool:
if i == n - 1 and j == m - 1:
return True
board[i][j] = 1
if i - 1 >= 0 and board[i - 1][j] == 0 and (i - 1, j) not in que:
que.append((i - 1, j))
if dfs(i - 1, j, que):
return True
if i + 1 < n and board[i + 1][j] == 0 and (i + 1, j) not in que:
que.append((i + 1, j))
if dfs(i + 1, j, que):
return True
if j - 1 >= 0 and board[i][j - 1] == 0 and (i, j - 1) not in que:
que.append((i, j - 1))
if dfs(i, j - 1, que):
return True
if j + 1 < m and board[i][j + 1] == 0 and (i, j + 1) not in que:
que.append((i, j + 1))
if dfs(i, j + 1, que):
return True
que.pop()
board[i][j] = 0
return False
que = [(0, 0)]
dfs(0, 0, que)
return que
if __name__ == '__main__':
n, m = map(int, input().split(' '))
board = []
for _ in range(n):
board.append(list(map(int, input().split(' '))))
ans = function(board)
for p in ans:
print('({},{})'.format(p[0], p[1]))
查看11道真题和解析
