LeetCode #743 - Network Delay Time

本文深入探讨了网络信号传播的时间延迟问题,通过分析N个网络节点间的信号传递时间,使用图论中的最短路径算法,解决如何计算从特定节点发送信号到所有节点所需最短时间的问题。文章详细介绍了算法实现过程,包括初始化网络边权重、计算各节点距离及优化路径选择等关键步骤。

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

题目描述:

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.

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        int result=0;
        vector<vector<int>> edge(N+1,vector<int>(N+1,-1));
        for(auto time:times) edge[time[0]][time[1]]=time[2];
        vector<int> distance(N+1,INT_MAX);
        queue<int> q;
        q.push(K);
        distance[K]=0;
        while(!q.empty())
        {
            int n=q.size();
            for(int i=0;i<n;i++)
            {
                int u=q.front();
                q.pop();
                for(int v=1;v<=N;v++) // 寻找从u->v的边
                {
                    if(edge[u][v]!=-1)
                    {
                        // 用距离关系来判断是否要访问一个节点,避免重复遍历,而不是用哈希表
                        // 从u->v的路径可以更新distance[v],那么v应该加入队列中,从而可以更新它的领接点
                        if (distance[v]>distance[u]+edge[u][v]) 
                        {
                            q.push(v);
                            distance[v]=min(distance[v],distance[u]+edge[u][v]);
                        }
                    }
                }
            }
        }
        for (int i=1;i<=N;i++) result=max(result,distance[i]);
        if(result==INT_MAX) return -1;
        else return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值