题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
import sys
result_path = []
def is_pos_legal(i:int, j:int, n:int, m:int):
return 0 <= i < n and 0 <= j < m
def avail(maze:list[list[int]], i:int, j:int, n:int, m:int):
return is_pos_legal(i, j, n, m) and maze[i][j] == 0
def need_visit(maze:list[list[int]], i:int, j:int, n:int, m:int, visited:set):
return avail(maze, i, j, n, m) and (i, j) not in visited
def search(maze:list[list[int]], cur_path:list, i:int, j:int, n:int, m:int, visited:set):
visited.add((i, j))
cur_path.append((i, j))
if i == n - 1 and j == m - 1:
return True
if need_visit(maze, i - 1, j, n, m, visited):
if search(maze, cur_path, i - 1, j, n, m, visited):
return True
if need_visit(maze, i + 1, j, n, m, visited):
if search(maze, cur_path, i + 1, j, n, m, visited):
return True
if need_visit(maze, i, j + 1, n, m, visited):
if search(maze, cur_path, i, j + 1, n, m, visited):
return True
if need_visit(maze, i, j - 1, n, m, visited):
if search(maze, cur_path, i, j - 1, n, m, visited):
return True
cur_path.pop()
return False
stack = []
n, m = [int(i) for i in input().split()]
visited = set()
maze = [[int(i) for i in input().split()] for i in range(n)]
search(maze, result_path, 0, 0, n, m, visited)
print("\n".join(["({},{})".format(i[0], i[1]) for i in result_path]))