蛮力法解决商旅问题算法能够接受包含任意顶点数和边数的无向图用文件形式输入图信息
以下是蛮力法解决商旅问题的Python代码,可以接受包含任意顶点数和边数的无向图输入:
import itertools
def tsp_brute_force(graph):
n = len(graph)
min_cost = float('inf')
min_path = None
for path in itertools.permutations(range(n)):
cost = 0
for i in range(n-1):
cost += graph[path[i]][path[i+1]]
cost += graph[path[-1]][path[0]]
if cost < min_cost:
min_cost = cost
min_path = path
return min_cost, min_path
if __name__ == '__main__':
# 从文件中读取图信息
with open('graph.txt', 'r') as f:
lines = f.readlines()
graph = []
for line in lines:
row = list(map(int, line.strip().split()))
graph.append(row)
# 计算最短路径
min_cost, min_path = tsp_brute_force(graph)
print('最短路径为:', min_path)
print('最短路径长度为:', min_cost)
其中,graph.txt文件中每行表示一行邻接矩阵,数字之间用空格隔开。例如,以下是一个5个节点的无向图的邻接矩阵,存储在graph.txt中:
0 2 3 4 5
2 0 6 7 8
3 6 0 9 10
4 7 9 0 11
5 8 10 11 0
运行以上代码即可输出最短路径和最短路径长度
原文地址: https://www.cveoy.top/t/topic/feeR 著作权归作者所有。请勿转载和采集!