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

相关推荐
excel9 小时前
watchEffect 为什么会执行两次?
前端
钱栈up12 小时前
两台机器、一个 AI 记忆库:101 秒把 137 个文件对齐
爬虫·python·数据分析
钱栈up12 小时前
外网通、QQ 登不上:一条 workbuddy 脚本塞进去的路由三天没还回来
爬虫·python·数据分析
AI创界者21 小时前
Python 进阶实战(七十三章):Python AI/LLM 应用工程化、流式响应与调用韧性实战
人工智能·python·aigc
Java展博1 天前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户112936112191 天前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼1 天前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_4191 天前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真1 天前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
青少儿编程课堂1 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛