【python 迪杰斯特拉-最短路径算法 可视化】

 - 算法实现

import heapq
import networkx as nx
import matplotlib.pyplot as plt


def dijkstra(graph, start, goal):
    distances = {node: float("infinity") for node in graph}
    distances[start] = 0
    parents = {node: None for node in graph}
    priority_queue = [(0, start)]

    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)

        if current_node == goal:
            break

        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                parents[neighbor] = current_node
                heapq.heappush(priority_queue, (distance, neighbor))

    path = []
    current_node = goal
    while current_node is not None:
        path.append(current_node)
        current_node = parents[current_node]
    path.reverse()

    return path, distances[goal]


# 示例图
graph = {
    "A": {"B": 1, "C": 4},
    "B": {"A": 1, "C": 2, "D": 5},
    "C": {"A": 4, "B": 2, "D": 1, "E": 2},
    "D": {"B": 5, "C": 1, "E": 3},
    "E": {"D": 3, "C": 2},
}

start_node = "A"
goal_node = "E"
shortest_path, shortest_distance = dijkstra(graph, start_node, goal_node)

print("从节点 {} 到节点 {} 的最短路径: {}".format(start_node, goal_node, shortest_path))
print("最短距离: {}".format(shortest_distance))

从节点 A 到节点 E 的最短路径: ['A', 'B', 'C', 'E']

最短距离: 5

- 可视化

# 创建一个网络图
G = nx.DiGraph()

# 将边添加到图中
for node, edges in graph.items():
    for neighbor, weight in edges.items():
        G.add_edge(node, neighbor, weight=weight)

# 设置图形布局
pos = nx.spring_layout(G)
# 绘制节点和边
nx.draw(
    G,
    pos,
    with_labels=True,
    node_color="lightblue",
    node_size=2000,
    font_size=16,
    font_weight="bold",
)

# 绘制边的权重
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(
    G, pos, edge_labels=edge_labels, font_color="red", font_size=15
)

# 将最短路径的边标识为红色
path_edges = [
    (shortest_path[i], shortest_path[i + 1]) for i in range(len(shortest_path) - 1)
]
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color="red", width=2)

# 显示图形
plt.title("Graph Visualization of Dijkstra's Algorithm")
plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

放飞自我的Coder

你的鼓励很棒棒哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值