题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
n, m = map(int, input().split())
maze = [input().split() for _ in range(n)]
def dfs(i, j, route=[(0, 0)]):
if i == n - 1 and j == m - 1:
for pos in route:
print("(" + str(pos[0]) + "," + str(pos[1]) + ")")
if j + 1 < m and maze[i][j + 1] == "0":
if (i, j + 1) not in route:
route.append((i, j + 1))
dfs(i, j + 1, route)
del route[-1]
if j - 1 >= 0 and maze[i][j - 1] == "0":
if (i, j - 1) not in route:
route.append((i, j - 1))
dfs(i, j - 1, route)
del route[-1]
if i + 1 < n and maze[i + 1][j] == "0":
if (i + 1, j) not in route:
route.append((i + 1, j))
dfs(i + 1, j, route)
del route[-1]
if i - 1 >= 0 and maze[i - 1][j] == "0":
if (i - 1, j) not in route:
route.append((i - 1, j))
dfs(i - 1, j, route)
del route[-1]
dfs(0, 0)
查看18道真题和解析