LeetCode: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.

 

Example 1:

Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

 

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 0 <= w <= 100.

 

算法一(Bellman Ford)

主要思路:外循环迭代N次,内循环对每一条边进行一次松弛操作。松弛操作:比如说对于某一个点i,di表示从起点到节点i的最短路径,那么如果di + (i节点到j节点的边长) < dj,则更新dj的值为di+边长。

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<int> d(N+1,0xfffffff);
        d[K] = 0;
        int edges =times.size();
        for(int i=1; i<=N; i++){
            for(int j=0; j<edges; j++){
                if(d[times[j][0]] + times[j][2] < d[times[j][1]]){
                    d[times[j][1]]= d[times[j][0]] + times[j][2];
                }
            }
        }
        int ret = 0;
        for(int i=1; i<N+1; i++){
            ret = max(ret,d[i]);
        }
        return ret == 0xfffffff? -1: ret;
    }
};

算法二(SPFA):

主要思路:Bellman Ford是遍历所有的边,SPFA是将所有收到影响的点添加到队列里,每次更新收到影响的点的值。

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<int> d(N+1,0xfffffff);
        vector<bool> isInQueue(N+1,false);
        vector<vector<pair<int,int>>> graph(N+1, vector<pair<int,int>>());
        for(int i=0; i<times.size(); i++){
            int u = times[i][0];
            int v = times[i][1];
            int w = times[i][2];
            graph[u].emplace_back(v,w);
        }
        queue<int>q;
        d[K] = 0;
        q.push(K);
        while(!q.empty()){
            int u = q.front(); q.pop();
            isInQueue[u] = false;
            for(auto &t: graph[u]){
                if(d[u]+t.second < d[t.first]){
                    d[t.first] = d[u] + t.second;
                    if(isInQueue[t.first] == false){
                        isInQueue[t.first] = true;
                        q.push(t.first);
                    }
                } 
            }
        }
        int ret = 0;
        for(int i=1; i<N+1; i++){
            ret = max(ret,d[i]);
        }
        
        return ret == 0xfffffff? -1: ret;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值