python - 找到两点之间的最短路径
问题描述
我想编写一个代码,可以找到起点和终点之间的最短路径。我写了一个代码,它没有错误,但它没有做我想要的。
它显示“运动”,但它没有在终点完成。
我该如何解决这个问题,如何包含“路径”需要从头到尾的条件?
你有下面的“地图”和代码的例子。
非常感谢。
代码:
import random
def shortestWay(n):
minx = 1
miny = 1
maxx = 5
maxy = 5
x_start = 1
y_start = 1
X_end = 3
Y_end = 5
for i in range (n):
way = random.choice(["up", "down", "left", "right"])
if way == "up" and y_start<maxy:
y_start +=1
elif way == "down" and y_start>miny:
y_start -=1
elif way == "left" and x_start>minx:
x_start -=1
elif way == "right" and x_start<maxx:
x_start += 1
if x_start == X_end and y_start == Y_end:
return(x_start,y_start)
x1 = x_start
y1 = y_start
return (x1, y1)
list1 = []
for i in range(25):
way = shortestWay(10)
theShortestWay = abs(way[0]) + abs(way[1])
list1.append(theShortestWay)
x = min (list1)
print(way, "distance from start: ", theShortestWay, "cells")
print ("Minimal distance: ", x)
解决方案
第一个函数“shortestWay(n)”在随机方向上进行 n 次迭代,很明显它可以降落在目的地 X,Y 之外的其他地方。例如,您应该根据当前与目标 X、Y 的距离制定算法。在每一步尝试使 abs(X_start - X_end) 和 abs(Y_start - Y_end) 尽可能小。
推荐阅读
- javascript - HTML5 Canvas 背景和颜色的实时预览
- java - 如何解决 javax.net.ssl.SSLHandshakeException:握手期间远程主机关闭连接
- python - 从随机选择的行返回文件行位置
- regex - 可执行文件上的 Gitignore
- asp.net-core - 在 dot net core3.1 中使用 IDataProtectionProvider 安全加密 appsettings 连接字符串
- php - 尝试使用 ErrorDocument 处理 symfony 5 中的请求时遇到 500 Internal Server Error 错误
- reactjs - 如何使用 reactjs 更改对象的值
- dart - 为什么 Dart 不能从 Crystal 解码 base64?
- django - 为项目和任务创建和更新 API(一对多关系) Django REST API(批量创建和更新)
- css - 如何使用 css 为单个材质 ui Grid 实例自定义 md 断点