python 图论最短路径

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

cpp 复制代码
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算法来计算从起始节点到其他所有节点的最短距离。最终返回一个包含最短距离的字典。

相关推荐
麻雀飞吧6 分钟前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy17 分钟前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.26 分钟前
【01】Python 机器学习
开发语言·python
AI_零食36 分钟前
番茄钟鸿蒙PC Electron框架完成:状态机、定时器管理与专注力工具设计
前端·javascript·华为·electron·开源·鸿蒙·鸿蒙系统
为爱停留36 分钟前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
提子拌饭13337 分钟前
逛三园游戏——基于鸿蒙PC Electron框架实现
前端·javascript·游戏·华为·electron·鸿蒙
llz_11239 分钟前
web-第三次课后作业
前端·后端·web
l1t1 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
遗憾随她而去.1 小时前
Web地图全体系深度梳理:引擎、数据源、图层、投影核心知识
前端
曾阿伦1 小时前
Python 搭建简易HTTP服务
开发语言·python·http