import matplotlib.pyplot as plt # 导入 Matplotlib 工具包
import networkx as nx # 导入 NetworkX 工具包
from typing import List
# 初始化空的无向图
graph = nx.Graph()
# 向图中添加多条赋权边: (node1,node2,weight)
graph.add_weighted_edges_from(
[
(1, 2, 50),
(1, 3, 60),
(2, 4, 65),
(2, 5, 40),
(3, 4, 52),
(3, 7, 45),
(4, 5, 50),
(4, 6, 30),
(4, 7, 42),
(5, 6, 70)
]
)
# 指定顶点位置
coordinates = {
1: (2.5, 10),
2: (0, 5),
3: (7.5, 10),
4: (5, 5),
5: (2.5, 0),
6: (7.5, 0),
7: (10, 5)
}
# 绘制无向图
# alpha:节点透明度
# node_color:节点颜色
# with_labels: 节点标签
nx.draw_networkx(graph, coordinates, with_labels=True, alpha=1)
labels = nx.get_edge_attributes(graph,'weight')
nx.draw_networkx_edge_labels(graph,coordinates,edge_labels=labels, font_color='c') # 显示权值
path:List = nx.dijkstra_path(graph, 1, 6)
print(path)
path:List = nx.astar_path(graph, 2, 6)
print(path)
plt.show()
改进的旅行商问题(TSP)是一个经典的组合优化问题,目标是找到一条最短的路径,使得旅行商能够访问一系列城市并返回起始城市。在解决这个问题时,可以使用networkx库来进行图的建模和求解。
networkx是一个用于创建、操作和研究复杂网络的Python库。它提供了许多图论算法和数据结构,可以用于解决旅行商问题。
"""
==========================
Traveling Salesman Problem
==========================
This is an example of a drawing solution of the traveling salesman problem
The function used to produce the solution is `christofides <networkx.algorithms.approximation.traveling_salesman.christofides>`,
where given a set of nodes, it calculates the route of the nodes
that the traveler has to follow in order to minimize the total cost.
"""
import matplotlib.pyplot as plt
import networkx as nx
import networkx.algorithms.approximation as nx_app
import math
G = nx.random_geometric_graph(20, radius=0.4, seed=3)
pos = nx.get_node_attributes(G, "pos")
# Depot should be at (0,0)
pos[0] = (0.5, 0.5)
H = G.copy()
# Calculating the distances between the nodes as edge's weight.
for i in range(len(pos)):
for j in range(i + 1, len(pos)):
dist = math.hypot(pos[i][0] - pos[j][0], pos[i][1] - pos[j][1])
dist = dist
G.add_edge(i, j, weight=dist)
cycle = nx_app.christofides(G, weight="weight")
edge_list = list(nx.utils.pairwise(cycle))
# Draw closest edges on each node only
nx.draw_networkx_edges(H, pos, edge_color="blue", width=0.5)
# Draw the route
nx.draw_networkx(
G,
pos,
with_labels=True,
edgelist=edge_list,
edge_color="red",
node_size=200,
width=3,
)
print("The route of the traveller is:", cycle)
plt.show()