迪杰斯特拉算法python实现--有向图

代码如下:

# -*- coding: utf-8 -*-
MAX_value = 999999

def dijkstra(graph, s):
    # 判断图是否为空,如果为空直接退出
    if graph is None:
        return None
    dist = [MAX_value] * len(graph)
    dist[s] = 0  # 记录最终的到各个点的最短路径长度
    S = []  # 已经走过的节点
    Q = [i for i in range(len(graph))]  # 记录有多少个节点
    dist_init = [i for i in graph[s]]  # 初始时的路线
    while Q:
        u_dist = {v: d for v, d in enumerate(dist_init) if v in Q}
        u = min(u_dist, key=u_dist.get)
        S.append(u)
        Q.remove(u)

        for v, d in enumerate(graph[u]):
            if 0 < d < MAX_value:
                if dist[v] > dist[u] + d:
                    dist[v] = dist[u] + d
                    dist_init[v] = dist[v]
    return dist


if __name__ == '__main__':
    graph_list = [[0, 9, MAX_value, MAX_value, MAX_value, 14, 15, MAX_value],
                  [9, 0, 24, MAX_value, MAX_value, MAX_value, MAX_value, MAX_value],
                  [MAX_value, 24, 0, 6, 2, 18, MAX_value, 19],
                  [MAX_value, MAX_value, 6, 0, 11, MAX_value, MAX_value, 6],
                  [MAX_value, MAX_value, 2, 11, 0, 30, 20, 16],
                  [14, MAX_value, 18, MAX_value, 30, 0, 5, MAX_value],
                  [15, MAX_value, MAX_value, MAX_value, 20, 5, 0, 44],
                  [MAX_value, MAX_value, 19, 6, 16, MAX_value, 44, 0]]

    distance = dijkstra(graph_list, 0)
    print(distance)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值