蛮力法求解旅行商问题:Python代码实现及图信息输入
本文介绍使用蛮力法解决旅行商问题(TSP)的 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/n6AI 著作权归作者所有。请勿转载和采集!