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

相关推荐
光影少年5 分钟前
三维前端需要会哪些东西
前端·webgl
代码or搬砖8 分钟前
HashMap源码
开发语言·python·哈希算法
王林不想说话1 小时前
React自定义Hooks
前端·react.js·typescript
heyCHEEMS1 小时前
Uni-app 性能天坑:为什么 v-if 删不掉 DOM 节点
前端
马致良1 小时前
三年前写的一个代码工具,至今已被 AI Coding 完全取代。
前端·ai编程
橙某人1 小时前
LogicFlow 交互新体验:让锚点"活"起来,鼠标跟随动效实战!🧲
前端·javascript·vue.js
借个火er1 小时前
依赖注入系统
前端
借个火er1 小时前
项目介绍与环境搭建
前端
gustt1 小时前
React 跨层级组件通信:从 Props Drilling 到 useContext 的实战剖析
前端·react.js
程序猿的程1 小时前
Stock写给前端的股票行情 SDK: stock-sdk,终于不用再求后端帮忙了
前端·javascript·node.js