题目内容
DFS代码
虽然求最短路径更应该用 BFS ,但是本题限定了只有唯一解,所以可以使用 DFS
# 四个方向移动
dirs = [
lambda x, y: (x+1, y),
lambda x, y: (x, y+1),
lambda x, y: (x-1, y),
lambda x, y: (x, y-1)
]
# x1, y1 为起点, x2, y2 为终点
def maze_path(x1, y1, x2, y2):
stack = []
stack.append((x1, y1))
# 当栈不为空时
while len(stack) > 0:
cur_node = stack[-1] # 当前节点为栈顶结点
# 如果走到终点,输出路径
if cur_node[0] == x2 and cur_node[1] == y2:
for i in stack:
print("({},{})".format(i[0]-1, i[1]-1))
break
# 往四个方向走
for dir in dirs:
next_node = dir