leetcode 743. Network Delay Time

本文介绍了一个算法问题:如何计算从特定节点发出信号后所有节点接收该信号所需的最长时间。通过BFS实现,确保只更新更优的时间记录,并利用map记录每个节点的最短到达时间。

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

743Network Delay Time

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.

Note:

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

1、BFS。如果到一个点,发现接下去要找的点到达的时间比之前到过的时间要短,才push进queue。不然没有意义。

2、map存到达时间。也可以当做bfs的hash表使用。


class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K)
    {
        int ret = INT_MIN;
        map<int, vector<pair<int, int> > > route;   //pair 存的是 终点-时间
        for (int i = 0; i < times.size(); i ++)
        {
            route[times[i][0]].push_back(make_pair(times[i][1], times[i][2]));
        }
        map<int, int> arrive_time;  //到达i点的最快时间。也可以当做hash表存已经遍历过的点
        arrive_time[K] = 0;
        queue<int> que;
        que.push(K);
        while (!que.empty())
        {
            int top = que.front();
            que.pop();
            for (int i = 0; i < route[top].size(); i++)
            {
                if (arrive_time.find(route[top][i].first) == arrive_time.end() ||
                    arrive_time[route[top][i].first] > arrive_time[top] + route[top][i].second
                    ) //第一次遍历 或 当前这个路径的时间更少,那就更新
                {
                    arrive_time[route[top][i].first] = arrive_time[top] + route[top][i].second;
                    que.push(route[top][i].first);
                }
            }
        }
        if (arrive_time.size() != N)
            return -1;
        for (auto it : arrive_time)
            ret = max(ret, it.second);
        return ret;
    }
};


### 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、付费专栏及课程。

余额充值