最短路径(迪杰斯特拉算法Dijkstra)python版本实现

import numpy as np

'''
    该版本迪杰斯特拉算法 只实现原点到终点的最短路径
    对中间其他点的最短路径没有做处理
'''


def get_shortest_route(start: int, data):
    # 获取最大路径值 用于排除
    max_value = np.max(mgraph)
    # 获取列表长度
    lenth = len(mgraph)
    # while循环记录位置
    cur_index = 0
    # 默认第一条路径就为 1
    result = [start]
    while True:
        # 获取单个列表
        cur_list = mgraph[cur_index]
        tmp_dict = {}
        # 遍历列表值 及其 下标
        for index, value in enumerate(cur_list):
            if value == 0 or value == max_value:
                continue
            tmp_dict[index + 1] = value
        # 对当前字典中的下标 及 值 进行筛选过滤
        tmp_key_list = tmp_dict.keys()
        if len(tmp_key_list) > 0:
            # 如果最大路径所在的下标已经存在 则遍历完成
            if lenth in result:
                return result
            else:
                min_value = min(tmp_dict.values())
                # 获取当前字典最小值 及其 下标
                for i in tmp_dict:
                    if tmp_dict[i] == min_value:
                        result.append(i)

        cur_index += 1
        if cur_index > lenth - 1:
            break


if __name__ == "__main__":
    inf = 10086
    mgraph = [[0, 2, 5, inf, inf],
              [inf, 0, 2, 6, inf],
              [inf, inf, 0, 7, 1],
              [inf, inf, 2, 0, 4],
              [inf, inf, inf, inf, 0]]
    start = 1
    result = get_shortest_route(start, mgraph)
    print(result)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值