(Python版)Dijkstra算法(包含朴素算法和堆优化)

最近要给俱乐部的成员做板子,所以专门写了一些代码方便理解背诵。代码注释很详细,并且对时间复杂度进行了详细的推导,希望大家看完后会有所收获。

# -*- coding : utf-8 -*-
"""
@author: 2023数据赋能俱乐部
@Description: 迪杰斯特拉算法
@Date: 2024-4-4 15:36
"""
import random
from heapq import heappop, heappush
from math import inf
from typing import List

# 本代码可以直接提交力扣2642测评
# https://leetcode.cn/problems/design-graph-with-shortest-path-calculator


class Graph:
    def __init__(self, n: int, edges: List[List[int]]):  # edges为有向边三元组(x, y, 权重)
        a = [[] for _ in range(n)]
        self.a = a; self.n = n

        # 邻接表
        for x, y, w in edges:
            a[x].append((w, y))

        # 邻接矩阵
        self.g = [[inf] * n for _ in range(n)]
        for x, y, w in edges:
            self.g[x][y] = w  # 添加一条边

    def addEdge(self, e: List[int]) -> None:
        x, y, w = e

        # 邻接表
        self.a[x].append((w, y))

        # 邻接矩阵
        self
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值