leetcode 743. Network Delay Time(网络延迟时间)

博客围绕网络节点消息传播问题展开,给出有向图及边的时间,求从节点K发出消息,所有节点收到消息的最短时间,若有点无法到达则返回 -1。采用Dijkstra算法,通过距离的relax操作更新最短路径,利用堆加速更新,最后找出最短路径中的最大值。

There are N network nodes, labelled 1 to N.

Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

Example 1:
在这里插入图片描述
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

Note:

N will be in the range [1, 100].
K will be in the range [1, N].
The length of times will be in the range [1, 6000].
All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.

给出一个有向图,每条边给出一个时间,求网络中所有点收到K发出的消息所需要的最短时间,如果有点无法到达就返回-1

思路:
即求从K点出发到所有点的最短路径,在所有最短路径中选最长的
这里用Dijkstra算法

Dijkstra算法是一种距离的relax算法,用dist(u, v)表示u到v的距离,用dist(u)表示出发点K到u的距离,那么
dist(v) = dist(u) + dist(u, v)
如果中间出现了另外一点u1,使
dist(v) > dist(u1) + dist(u1, v)
就更新 dist(v) 到新的最短距离dist(u1) + dist(u1, v)

为了更加快速更新,每更新一个最短距离,保存(u, dist[u]) 到heap中,每次取出最小的dist[u],遍历u可到达的每一个点v,更新dist(v)到新的最短路径
同时用一个数组dist,保存K到每个节点的最短距离,最后可通过遍历这个数组,找出最短路径中的最大值。dist初始化为∞,当最后仍然存在∞时,说明有点不可到达,返回-1。

Dijkstra算法
在这里插入图片描述

    public int networkDelayTime(int[][] times, int N, int K) {
        HashMap<Integer, List<int[]>> graph = new HashMap<>();
        PriorityQueue<int[]> heap = new PriorityQueue<>(
            (i1, i2) -> i1[1] - i2[1]);
        int[] dist = new int[N+1];
        int inf = 1000000000;
        int result = 0;
        
        Arrays.fill(dist, inf);        
        dist[K] = 0;
        heap.offer(new int[]{K, 0});
        
        //make the graph(有向图)..
        for(int[] time : times) {
            if(!graph.containsKey(time[0])) {
                graph.put(time[0], new ArrayList<int[]>());
            }
            graph.get(time[0]).add(new int[]{time[1], time[2]});
        }
        
        while(!heap.isEmpty()) {
            int[] nodeU = heap.poll();
            int u = nodeU[0];
            int distU = nodeU[1];
            if(!graph.containsKey(u)) continue;
            List<int[]> nodeVs = graph.get(u);
            
            for(int[] nodeV : nodeVs) {
                int v = nodeV[0];
                int distUV = nodeV[1];
                if(dist[v] > distU + distUV) { //dist(u) + dist(u,v)
                    dist[v] = distU + distUV;
                    heap.offer(new int[]{v, dist[v]});
                }
            }
        }
        
        for(int i = 1; i <= N; i++) {
            if(dist[i] == inf) return -1;
            result = Math.max(result, dist[i]);
        }
        
        return result;
    }
### Dijkstra算法相关的LeetCode题目 Dijkstra算法主要用于解决单源最短路径问题,适用于加权图中的路径计算。以下是与Dijkstra算法密切相关的LeetCode题目: #### 题目一:网络延迟时间 (Network Delay Time) 这是一道经典的Dijkstra算法应用题,目标是找到信号从起点传播到所有节点所需的最长时间。如果无法到达某些节点,则返回 `-1`[^1]。 ```python import heapq from collections import defaultdict def networkDelayTime(times, n, k): graph = defaultdict(list) for u, v, w in times: graph[u].append((v, w)) dist = {node: float('inf') for node in range(1, n + 1)} dist[k] = 0 heap = [(0, k)] while heap: current_dist, u = heapq.heappop(heap) if current_dist > dist[u]: continue for v, weight in graph[u]: distance = current_dist + weight if distance < dist[v]: dist[v] = distance heapq.heappush(heap, (distance, v)) max_time = max(dist.values()) return max_time if max_time != float('inf') else -1 ``` 此代码实现了基于优先队列优化的Dijkstra算法来解决问题。 --- #### 题目二:最低成本连接所有城市 (Min Cost to Connect All Points) 虽然该题主要涉及Kruskal或Prim算法,但在特定情况下也可以通过构建完全图并使用Dijkstra算法求解[^2]。不过需要注意的是,这种方法效率较低,通常不推荐作为首选方案。 --- #### 题目三:最便宜航班 (Cheapest Flights Within K Stops) 尽管本题可以通过Bellman-Ford或者BFS方法解答,但采用修改版的Dijkstra同样可行。区别在于需要增加状态维度以记录剩余跳跃次数[^5]。 ```python def findCheapestPrice(n, flights, src, dst, k): graph = defaultdict(list) for u, v, p in flights: graph[u].append((v, p)) pq = [(0, src, k + 1)] # price, vertex, stops remaining while pq: cost, city, steps_left = heapq.heappop(pq) if city == dst: return cost if steps_left > 0: for neighbor, price in graph[city]: new_cost = cost + price heapq.heappush(pq, (new_cost, neighbor, steps_left - 1)) return -1 ``` 上述实现展示了如何扩展传统Dijkstra逻辑适应更多约束条件下的场景需求[^5]。 --- ### 总结 以上列举了几类适合练习Dijkstra算法的经典LeetCode题目及其对应解决方案概览。每种变体都体现了不同实际应用场景下对该基础理论框架的具体调整运用方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值