![b334ddd1e1228f4926f6f2abda140389.png](https://i-blog.csdnimg.cn/blog_migrate/b94b269686541e1712131928c3897667.jpeg)
ortools是谷歌的一个开源框架,这里笔者用的是Python版本,去解决一个已知距离矩阵,求最短路径的问题。最短路径,也就是travel saleman problem,是指一个旅行商想一次走遍所有的目的地,同时花费最短的距离或时间。抽象来说既是在一个连通图上,求n个节点的最短路径。
首先贴上官方的代码,python3.6可跑通
https://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/tsp_cities.pygithub.com这个代码的一个问题是计算了回程的路径,实际上很多最短路径问题不需要计算。那么我们要知道ortools的vrp问题是通过distance_callback函数来传入距离的。因此针对返回节点 to node等于0的情况,我们可以设置距离成本为0。
def
也就是修改回程距离为0。继续运行,结果为
Objective: 5765 miles
Route for vehicle 0:
0 -> 7 -> 2 -> 3 -> 9 -> 10 -> 5 -> 4 -> 12 -> 11 -> 1 -> 8 -> 6 -> 0
修改print solution,把经过的站点和距离加入list中,最后return出来。
def print_tsp_solution(manager, routing, solution):
"""Prints solution on console."""
print('Objective: {} miles'.format(solution.ObjectiveValue()))
index = routing.Start(0)
plan_output = 'Route for vehicle 0:n'
route_distance = 0
route = []
cost = []
while not routing.IsEnd(index):
plan_output += ' {} ->'.format(manager.IndexToNode(index))
route.append(manager.IndexToNode(index))
previous_index = index
index = solution.Value(routing.NextVar(index))
route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)
cost.append(routing.GetArcCostForVehicle(previous_index, index, 0))
plan_output += ' {}n'.format(manager.IndexToNode(index))
print(plan_output)
plan_output += 'Route distance: {}milesn'.format(route_distance)
# [END solution_printer]
return route,cost
修改main函数名字(略)。
我们可以自定义一个建立距离矩阵的函数,输入是poi的经纬度列表,输出是距离矩阵。
注意这里的参数第一个元素是起点,其他元素是各个配送终点。
def
gaode_geodistance_poi是我自己调用高德计算的骑行距离,key我已经隐藏了。需要的小伙伴自行去高德开发平台注册一个。
最后做少许修改,就可以用get_short_dist_by_pois来计算n个poi坐标的最短距离了。全部代码如下。有问题的留言我。
from