Network Delay Time - LeetCode

本文介绍了一道LeetCode上的经典算法题“Network Delay Time”的解决方案。该问题旨在求解信号从指定节点发送到图中所有节点所需的最短时间。通过采用Dijkstra算法,并利用C++实现,有效地解决了这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Network Delay Time - LeetCode

题目
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.


考前刷的一道题,正好考试考到了,可惜没有打印出来。
题目会给出一幅图中各条边权值,然后给出一个起点,从起点发出一个信号,经过多长时间能够到达所有点。
这道题就是要求起点到最远点的最短距离,用dijkstra算法就能得出结果。

在代码中我使用了set< pair<int, int> >这样的结构来记录待遍历节点。
pair.first是cost,pair.second是节点的序号。
由于set会自动排序,会按照cost从小到大来排,最大的好处是可以记录下cost与节点的对应关系

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int start) {
        start -= 1;
        int n = N;
        int canNotReach = 99999999;
        vector< vector<int> > g(n, vector<int>(n,canNotReach));
        for (int i = 0; i < times.size(); i++) {
            g[times[i][0]-1][times[i][1]-1] = times[i][2];
        }
        // int n = g.size();
        vector<int> dist(n, canNotReach);
        vector<int> prev(n, -1);
        dist[start] = 0;
        set< pair<int, int> > s;
        s.insert(make_pair(0, start));
        set< pair<int,int> >::iterator it;
        int maxd = 0;
        int count = 0;
        while (!s.empty()) {
            count++;
            int mind = (*s.begin()).first;
            maxd = max(maxd, mind);
            int node = (*s.begin()).second;
            s.erase(s.begin());
            for (int i = 0; i < n; i++) {
                if (mind+g[node][i] < dist[i]) {
                    dist[i] = mind+g[node][i];
                    prev[i] = node;
                    for (it = s.begin(); it != s.end(); it++) {
                        if ((*it).second == i) {
                            s.erase(it);
                            break;
                        }
                    }
                    s.insert(make_pair(dist[i], i));
                }
            }
        }
        if (count < n) return -1;
        return maxd;
    }
};
### 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值