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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值