python - 我有 4 点,我想找到给定起点的最短路径
问题描述
x1 = 7
y1 = 5
x2 = 8
y2 = 7
x3 = 12
y3 = 9
x4 = 13
y4 = 12
import math
d1 = math.sqrt(x2 - x1)**2 + (y2 - y1)**2
d2 = math.sqrt(x3 - x1)**2 + (y3 - y1)**2
d3 = math.sqrt(x4 - x1)**2 + (y4 - y1)**2
d4 = math.sqrt(x3 - x2)**2 + (y3 - y2)**2
d5 = math.sqrt(x4 - x2)**2 + (y4 - y2)**2
d6 = math.sqrt(x4 - x3)**2 + (y4 - y3)**2
distances = [(d1 + d5 + d6 + d2), (d3 + d6 + d4 + d1)]
print(f"the shortest path is {min(distances)} cm and the longest path is {max(distances)} cm")
通过这样做,我将起点设置为X1
, Y1
,并且我基本上将这些点连接起来。x1,y1
但是,如果我需要找到通过n
点的距离怎么办,x1 y1
这是给定的。我应该怎么做才能优化流程?谢谢你。
解决方案
优化是使用带堆的 Prim 算法
代码
from heapq import heappush, heappop
def find_min_path(points):
'''
min path starting at points[0] using Prim's heap based algorithm
'''
def distance(p1, p2):
' Distance between two points in 2D '
d = (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2
return d**0.5
h = [] # Empy heap
path = [points[0]] # Add first point to path
heappush(h, (0, path)) # Add to heap tuple of (distance, path)
while h:
# Expand path with smallest total distance
d, path = heappop(h)
if len(path) == len(points):
# Completed path
break
for p in points[1:]:
# for all points not in starting point
if not p in path:
# Extend if point p not in path
# distance increases by distance to last point in path to p
# path extended by p
heappush(h, (d + distance(p, path[-1]), path + [p]))
return d, path
测试
# List of 2D points
points = [(7, 5), (8, 7), (12, 9), (13, 12)]
d, path = find_min_path(points)
print(f'Min Distance {d:.4f} using path {*path,}')
输出
Min Distance 9.8705 using path ((7, 5), (8, 7), (12, 9), (13, 12))
推荐阅读
- vb.net - VB.NET 输入值不足时弹出消息框
- ajax - 将我获取的数据存储到我的数组 const = player
- python-3.x - 如何使用networkx中的用户节点从txt文件添加用户属性
- c++ - 如何静态编译多个 Windows dll 和 libstdc++?
- typescript - TypeScript 4.2.1 Array.some() 不接受返回布尔值的函数
- python - Azure Functions Blob 部署
- javascript - 在 javascript 中重新映射对象数组
- php - 如何在php中小写我的标题的第一个字母?
- javascript - 覆盖 Object.entries() 的类型会导致意外错误
- reactjs - 重新导出所有内容均未按预期工作 - 导入另一个文件时出现问题