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

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python