图中的复杂算法

本文详细介绍了图算法中的关键概念,包括Dijkstra算法求最小距离,拓扑排序判断有向图无环,强连接元素的探讨,最小生成树的构建以及BFS过程中记录最短路径的方法。这些算法在图论和数据结构中扮演着重要角色,对于理解和解决复杂问题至关重要。
摘要由CSDN通过智能技术生成

1.求最小距离 Dijkstra algorithm

其实就是一个BFS问题,只是BFS运行的时候每次是入queue,Dijkstra每次是入heap(每次出最小的)。

1. 初始化 disTo 为所有都为 正无穷, 除了起始点为0。

2. 初始化 heapq 为所有以出发点为起点的边。

3. 如果disTo[v] > disTo[u] + dis(当找到一个更小的距离), 更新距离,并且把其所有边加入heap

4. 直到heap为空

class Solution:
    def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
        graph = {}
        disTo = {}
        pq = []
        # 1. build the graph
        # 2. make distance to every point infinity
        for time in times:
            
            start = time[0]
            end = time[1]
            dis = time[2]
            
            disTo[start] = float("inf")
            disTo[end] = float("inf")
            
            if start not in graph:
                graph[start] = [[dis, end]]
            else:
                graph[start].append([dis, end])
                
            if start == K:
                heapq.heappush(pq, [dis, start, end])
        # init the pq with start point with dis = 0
        
        
        disTo[K] = 0
        while pq:
            this = heapq.heappop(pq)
            
            u = this[1]
            v = this[2]
            dis = this[0]
            
            #加入新的路径小于之前的路径,则更新,并且将子节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值