Leetcode 743. Network Delay Time

来源:互联网 发布:floydwarshall 算法 编辑:程序博客网 时间:2024/06/06 05:53

题目描述:
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.

题目分析:
Leetcode上medium难度的题目:找从一个节点到另外所有节点的最短路径,典型的做法就是dijkstra算法,每次找到一个离源节点最近的节点,然后利用它更新其他节点到目标节点的最短距离,即如果graph[K][j] + graph[j]i] < graph[K][i],则graph[K][i]更新为graph[K][j] + graph[j][i],再进行下一轮取新的离目标节点最近的节点,直到所有其他节点都找到了一条到目标节点的最短路径为止。

具体步骤:

  • step1:将times用图的路径形式保存在二维数组中,两点间没有路径的则设为max值999表示无穷远。
  • step2:用一个数组保存所有要到达的节点,如果找到最短路径了,则将此节点从数组中删除。
  • step3:每一轮先找出离K节点最近的节点,假如没有节点可以到达K,则返回-1。用if (graph[K][j] + graph[j][*it] < graph[K][*it]){graph[K][*it] = graph[K][j] + graph[j][*it];}更新其它点到k的最短路径值,再找距离最小的点,直到节点数组为空。
  • step4:返回最后一个找到最短距离的点离K的距离。

详细代码

#include <iostream>using namespace std;#include <vector>class Solution {public:    int networkDelayTime(vector<vector<int> >& times, int N, int K) {        /*将times用图的路径形式保存在二维数组中*/         vector<vector<int> > graph(N + 1, vector<int>(N + 1, 999));        for (int i = 0; i < times.size(); i++){            int u = times[i][0];            int v = times[i][1];            int t = times[i][2];            graph[u][v] = t;        }        /*用一个数组保存所有目标节点*/         vector<int> des;        for (int i = 1; i < K; i++) des.push_back(i);        for (int i = K + 1; i <= N; i++) des.push_back(i);        int min;        while (!des.empty()){            /*找出当前离k最近的节点*/             min = graph[K][des[0]];            int min_pos = des[0];            vector<int>::iterator temp = des.begin();            for (vector<int>::iterator it = des.begin() + 1; it != des.end(); it++){                if (graph[K][*it] < min){                    temp = it;                    min_pos = *it;                    min = graph[K][*it];                }            }            if (min == 999) return -1;  /*没有点可达,返回-1*/             int j = min_pos;            des.erase(temp);            for (vector<int>::iterator it = des.begin(); it != des.end(); it++){                /*更新其它点到k的最短路径值*/                 if (graph[K][j] + graph[j][*it] < graph[K][*it]){                     graph[K][*it] = graph[K][j] + graph[j][*it];                }            }        }        return min;    }};
原创粉丝点击