题解 | #迷宫问题#
迷宫问题
https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
m, n = map(int, input().split())
maze = []
for i in range(m):
maze.append(list(map(int, input().split())))
# dirs = [
# lambda x,y: (x+1, y),
# lambda x,y: (x-1, y),
# lambda x,y: (x, y+1),
# lambda x,y: (x, y-1)
# ]
# 上述dir方法等同于:
def ne_point(x,y):
return [(x, y+1),(x+1, y),(x, y-1),(x-1, y)]
def maze_path(x1, y1, x2, y2): #开始坐标和结束坐标
stack = []
stack.append((x1,y1))
while stack:
cur_point = stack[-1]
if cur_point[0] == x2 and cur_point[1] == y2: #当前节点是最后一个点的坐标时候,证明找到了家
for p in stack:
print('(' + str(p[0]) + ',' + str(p[1]) + ')')
return True
for next_point in ne_point(cur_point[0],cur_point[1]):
if (0 <= next_point[0] <= m-1) and (0 <= next_point[1] <= n-1): #保证索引没有越界
if maze[next_point[0]][next_point[1]] == 0: # 找到了下一个可以走的节点
stack.append(next_point) # 入栈
maze[next_point[0]][next_point[1]] = 2 #标记为已遍历
break # 终止for循环,while循环不影响
else:
stack.pop() #当前节点出栈
maze[cur_point[0]][cur_point[1]] = 2 # 将当前节点标记为已遍历
else:
# 证明stack为空,也就说没有找到家,死胡同
return False
maze_path(0, 0, m-1, n-1)

