算法——Week8

本文探讨了网络延迟时间问题,给出了使用Bellman-Ford算法解决该问题的具体步骤。在一个包含N个节点的网络中,从特定节点K发送信号,如何计算所有节点接收到信号的时间,若无法接收则返回-1。

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

743. Network 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:
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 1 <= w <= 100.


解题思路
使用Bellman-Ford算法来求最短路径。

  1. 首先将源点K到其他节点的路径长度设为无穷大(本题中设置为了10000表示无穷大)。
  2. 遍历所有节点对,如果这对节点中的源节点已经被遍历(即K到其距离小于无穷),则这对节点中的目标节点可以达到。
  3. 比较这对节点中的目标节点的路径长和源节点加权值的大小。
  4. 遍历N-1次后结束。
  5. 如果路径中存在无穷大,则表明有的节点是不可达的,返回-1,否则返回路径中最大的一个。

代码如下:

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<int> dist(N+1, 10000);
        dist[K] = 0;
        int max_loop = times.size();
        int t = 1;
        int full_loop = 0;
        while(t++ && full_loop < N) {
            if(t > max_loop + 1) {
            	full_loop++;
                t = 2;
            }
            vector<int> time = times[t-2];
            int u = time[0];
            int v = time[1];
            int w = time[2];
            if(dist[u] != 10000 && dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                continue;
            }
        }
        int result = 0;
        for(int i = 1; i <= N; i++) {
            if(dist[i] > result) {
                result = dist[i];
            }
        }
        if(result == 10000) {
            result = -1;
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值