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.

解题思路

最重要的就是理解题意,题目的意思是:当信号到达了一个结点时,在下一刻可以同时转发给该结点相邻的所有结点,求传送到每一个结点的最终时间。这样,问题就变成了求解从结点 K 到所有结点的单源最短路问题,然后,从中选择最长的一条路所用的时间即为答案。因此本题使用 Dijkstra 算法进行求解。需要注意的是每次从所有的路径中选择最短路径的结点出来后,要将该结点设置为已访问,避免再重复访问。

C++代码实现

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<vector<int> > graph(N + 1, vector<int>(N + 1, 60001));
        vector<int> cost(N + 1);
        vector<bool> visited(N + 1, false); 

        for (int i = 0; i < times.size(); ++i) { graph[times[i][0]][times[i][1]] = times[i][2]; }
        for (int i = 1; i <= N; ++i) { cost[i] = graph[K][i]; }
        cost[K] = 0;
        visited[K] = true;

        for (int i = 1; i <= N; ++i) {
            int minNode = findMinNode(cost, visited);
            if (minNode == 0) { break; }
            for (int j = 1; j <= N; ++j) {
                if (!visited[j] && cost[j] > cost[minNode] + graph[minNode][j]) {
                    cost[j] = cost[minNode] + graph[minNode][j];
                }
            }
            visited[minNode] = true;
        }

        return calSum(cost);
    }

    int findMinNode(vector<int>& cost, vector<bool>& visited) {
        int minIndex = 0, minV = 60001;
        for (int i = 1; i < cost.size(); ++i) {
            if (!visited[i] && minV > cost[i]) { 
                minIndex = i; 
                minV = cost[i];
            }
        }

        return minIndex;
    }

    int calSum(vector<int>& cost) {
        int sum = 0;
        for (int i = 1; i < cost.size(); ++i) {
            if (cost[i] == 60001) { return -1; }
            if (sum < cost[i]) { sum = cost[i]; }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值