python 图论最短路径

在图论中,有许多算法可以用来求解最短路径问题,其中最著名的算法之一是Dijkstra算法。Dijkstra算法用于求解从一个顶点到其他所有顶点的最短路径,它适用于有向无环图(DAG)或无负权边的图。

import heapq

def dijkstra(graph, start):
    distances = {node: float('infinity') for node in graph}  # 初始化所有节点到起始点的距离为无穷大
    distances[start] = 0  # 起始点到自身的距离为0
    pq = [(0, start)]  # 优先队列,用于存储节点的距禧和节点的值
    while pq:
        current_distance, current_node = heapq.heappop(pq)  # 从优先队列中取出当前距禧最小的节点
        if current_distance > distances[current_node]:  # 如果当前距离已经大于最短距离,则跳过
            continue
        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))
    return distances

# 测试示例
graph = {
    'A': {'B': 5, 'C': 2},
    'B': {'A': 5, 'C': 1, 'D': 3},
    'C': {'A': 2, 'B': 1, 'D': 6},
    'D': {'B': 3, 'C': 6}
}
start_node = 'A'
shortest_distances = dijkstra(graph, start_node)
print(f"从节点 {start_node} 到其他所有节点的最短距离为:")
for node, distance in shortest_distances.items():
    print(f"节点 {node}: {distance}")

在上面的示例中,dijkstra函数接受一个图(以字典形式表示)和一个起始节点作为参数,然后使用Dijkstra算法来计算从起始节点到其他所有节点的最短距离。最终返回一个包含最短距离的字典。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ma_si

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值