题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
def dfs(i, j):
#x,y的4个方向
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
#判断是否已到终点,如果已经达到,则将访问的点都打印出来
if i == m - 1 and j == n - 1:
for pos in route:
print('(' + str(pos[0]) + ',' + str(pos[1]) + ')')
return
#通过for循环,判断当前点向四周出发的点情况,顺序为左,右,上,下
for k in range(4):
x = i + dx[k]
y = j + dy[k]
#判断要移动的点,是否能够访问
if x >= 0 and x < m and y >= 0 and y < n and map1[x][y] == 0:
#访问过的点都设为1,避免走回头路
map1[x][y] = 1
#访问过的点添加到route中
route.append((x, y))
#再基于当前访问的点,搜寻可访问的点
dfs(x, y)
#return返回后的继续从这执行,开始回退原路,重新将访问过的点变回0(未访问状态),同时将坐标从路径route中去掉,直到回到上个路口
map1[x][y] = 0
route.pop()
#既没到终点,同时当前点 无法向四周移动,那么就返回return,结束当前的dfs函数。开始回退原路
else:
return
while True:
try:
m, n = list(map(int, input().split()))
map1 = []
for i in range(m):
s = list(map(int, input().split()))
map1.append(s)
#初始值是(0,0)将其标记为已经访问过的点
route = [(0, 0)]
#起始点设为1,表示访问过,保证dfs时候不会走原路径
map1[0][0] = 1
#从起始点出发,使用dfs寻找下一个访问的点
dfs(0, 0)
except:
break