[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.

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算法:我们首先构造二维邻接矩阵,表示结点和结点之间的连接关系。然后采用BFS的方法,遍历从结点K到所有其它结点的距离。最后选出距离最大者即可。由于需要构造邻接矩阵,所有算法的空间复杂度为O(n^2)。

2、Floyd算法:图论中有个Floyd算法特别简明。该算法是计算节点两两之间的最短距离的,我们也可以用来计算从结点K到所有其它结点之间的距离。也就是说,如果发现d[v] > d[u] + w,并且从u到v的距离是w,那么就更新d[v]的距离。最后我们遍历一遍从结点K到所有其它结点的最大距离,选出最大值即可。这里算法的空间复杂度为O(n),但是由于涉及到很多无效的计算,所有实际上算法的效率还不如BFS(但是该算法对于计算所有结点之间的两两距离很有效)。

代码

1、BFS算法:

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<int> sigTime(N, INT_MAX);
        vector< vector<int> > mat(N, vector<int>(N, -1));    //adjacent matrix
        for(auto edgeVec : times) {
            mat[ edgeVec[0] - 1][ edgeVec[1] - 1] = edgeVec[2];
        }
        K = K - 1;
        sigTime[K] = 0;
        queue<int> nodeQ;
        nodeQ.push(K);
        while(!nodeQ.empty()) {
            int nd = nodeQ.front();
            for(int i=0; i<N; ++i) {
                if (mat[nd][i] >= 0 && sigTime[i] > sigTime[nd] + mat[nd][i]) {
                    nodeQ.push(i);
                    sigTime[i] = sigTime[nd] + mat[nd][i];
                }
            }
            nodeQ.pop();
        }
        int ans = 0;
        for(auto t : sigTime) {
            ans = max(t, ans);
        }
        return (ans == INT_MAX) ? -1 : ans;
    }
};

2、Floyd算法:

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<int> dist(N + 1, INT_MAX);   // initial distances
        dist[K] = 0;
        for (int i = 0; i < N; ++i) {
            for (auto time : times) {
                int u = time[0], v = time[1], w = time[2];
                if (dist[u] != INT_MAX && dist[v] > dist[u] + w) {
                    dist[v] = dist[u] + w;
                }
            }
        }
        int max_wait = 0;
        for (int i = 1; i <= N; ++i) {
            max_wait = max(max_wait, dist[i]);
        }
        return max_wait == INT_MAX ? -1 : max_wait;
    }
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值