旅行商问题(TSP)即给定一组城市以及每对城市之间的距离,需要找到一条最短的路线,该路线只对每个城市进行一次访问并返回起点。
这里注意汉密尔顿活路(Hamiltonian Cycle)和TSP之间的区别。汉密尔顿回路问题是要找出是否存在一次游览每个城市一次的路线。在TSP问题中,我们是已知存在汉密尔顿回路(因为该图是完整的),并且实际上,存在许多此类回路,TSP问题在于找到最小权重的汉密尔顿回路。
例如,考虑下图中的图形。图中的TSP回路应该是1-2-4-3-1。游览费用为10 + 25 + 30 + 15,即80。
该问题是一个著名的NP难题。
本文讨论一个简单解决方案的实现,如下:
将城市1作为起点和终点。 由于路线是循环的,因此我们可以将任何点视为起点。
生成所有(n-1)个! 城市的序列。
计算每个序列的成本,并跟踪最小的排列成本,最后以最小的成本返回序列。
代码如下:
from sys import maxsize
from itertools import permutations
V = 4
# implementation of traveling Salesman Problem
def travellingSalesmanProblem(graph, s):
# store all vertex apart from source vertex
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
# store minimum weight Hamiltonian Cycle
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
# store current Path weight(cost)
current_pathweight = 0
# compute current path weight
k = s
for j in i:
current_pathweight += graph[k][j]
k = j
current_pathweight += graph[k][s]
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s = 0
print(travellingSalesmanProblem(graph, s))
输出为:
80