查找最短路径#

使用 shortest_path 函数在给定图的两个节点之间查找最短路径。

plot shortest path
['A', 'H', 'G', 'F', 'E']

import networkx as nx
import matplotlib.pyplot as plt

# 创建一个包含节点和边的图
G = nx.Graph()
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
G.add_edge("A", "B", weight=4)
G.add_edge("A", "H", weight=8)
G.add_edge("B", "C", weight=8)
G.add_edge("B", "H", weight=11)
G.add_edge("C", "D", weight=7)
G.add_edge("C", "F", weight=4)
G.add_edge("C", "I", weight=2)
G.add_edge("D", "E", weight=9)
G.add_edge("D", "F", weight=14)
G.add_edge("E", "F", weight=10)
G.add_edge("F", "G", weight=2)
G.add_edge("G", "H", weight=1)
G.add_edge("G", "I", weight=6)
G.add_edge("H", "I", weight=7)

# 找到从节点A到节点E的最短路径
path = nx.shortest_path(G, "A", "E", weight="weight")
print(path)

# 创建最短路径中的边列表
path_edges = list(zip(path, path[1:]))

# 创建所有边的列表,并根据它们是否在最短路径中来分配颜色
edge_colors = [
    "red" if edge in path_edges or tuple(reversed(edge)) in path_edges else "black"
    for edge in G.edges()
]

# Visualize the graph
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos, edge_color=edge_colors)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(
    G, pos, edge_labels={(u, v): d["weight"] for u, v, d in G.edges(data=True)}
)

plt.show()

Total running time of the script: (0 minutes 0.042 seconds)

Gallery generated by Sphinx-Gallery