[LeetCode]743. Network Delay Time

栏目: 编程工具 · 发布时间: 6年前

内容简介:There areGivenNow, we send a signal from a certain node

原题

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 .

题解

Dijskra

本题是典型的求解最短路径的问题,我们可以用Dijsktra方法进行求解。

Dijskra原理见: https://www.youtube.com/watch?v=NLp9C7AvJhk&t=524s

维基百科: https://zh.wikipedia.org/zh/%E6%88%B4%E5%85%8B%E6%96%AF%E7%89%B9%E6%8B%89%E7%AE%97%E6%B3%95

代码

typedef pair<int, int> pii;

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<vector<pii>> nodes(N + 1, vector<pii>{});
        for (auto time : times) {
            nodes[time[0]].push_back(make_pair(time[1], time[2]));
        }
        // declare vars
        priority_queue<pii, vector<pii>, greater<pii> > pq; // pii 0 for city index, 1 for cost time
        pq.push(make_pair(K, 0));
        vector<int> time(N + 1, INT_MAX);
        time[K] = 0;
        while (!pq.empty()) {
            pii node = pq.top();
            pq.pop();
            // update the time for the sub-nodes
            for (auto snode : nodes[node.first]) {
                if (time[snode.first] > time[node.first] + snode.second) {
                    time[snode.first] = time[node.first] + snode.second;
                    // add the valid sub-node to priority_queue
                    pq.push(make_pair(snode.first, time[snode.first]));
                }
            }
        }
        int a = -1;
        for (int i = 1; i < time.size(); ++i) {
            if (a < time[i]) a = time[i];
        }
        return a == INT_MAX ? -1 : a;
    }
};

复杂度分析

E代表times的长度

时间复杂度:O(ElogE)

空间复杂度:O(E + N)

原题: https://leetcode.com/problems/network-delay-time/

文章来源:胡小旭=>  [LeetCode]743. Network Delay Time

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms and Theory of Computation Handbook

Algorithms and Theory of Computation Handbook

Mikhail J. Atallah (Editor) / CRC-Press / 1998-09-30 / USD 94.95

Book Description This comprehensive compendium of algorithms and data structures covers many theoretical issues from a practical perspective. Chapters include information on finite precision issues......一起来看看 《Algorithms and Theory of Computation Handbook》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试