LeetCode | 743. Network Delay Time | 中等难度 图论 单源最短路径题

来源:互联网 发布:steam mac 中文游戏 编辑:程序博客网 时间:2024/06/01 10:41

743. Network Delay Time

My SubmissionsBack to Contest

·       User Accepted:518

·       User Tried:839

·       Total Accepted:531

·       Total Submissions:2331

·       Difficulty:Medium

Thereare 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 wis the time it takes for a signal totravel from source to target.

Now,we send a signal from a certain node K. How long will it take for all nodesto 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.

这题是图论单源最短路径题目,简单来说这题就是给出一个网络,和一个源点,计算每一个节点到源点的最短距离,然后输出这些最短距离里面最大的一个。我使用的是dijkstra算法

这是一道单源最短路径的题目,有种解法,可以使用广度优先遍历和深度优先遍历,只不过在遍历到已经访问过得节点的时候需要判断是否需要重新更新节点到源点的距离,可以使用dijkstra算法,可以使用bellman-ford算法,可以使用SPFA算法,

不过这一题有bug,题目说了1<=w<=100,可是在测试数据里面出现了w==0的数据,这一个bug导致了我之前的代码一直不通过,最后才发现了这个bug,

需要注意的是,int edges[101][101]= { -1 };这一句会导致edges除了第一个数为-1以外其他数都是0,int edges[101][101]= { 0 };会导致全部数据都是0,这一点需要注意,还有就是要会将二维数组转换成vector,这是有一个公式的

class Solution {

    #include <queue>

public:

    intnetworkDelayTime(vector<vector<int>>& times, int N, int K) {

  int inf = 20000;

      int edges[101][101] = { -1 };

      bool vst[101] = { 0 };

      int path[101];

      int prev[101] = { 0 };

     

      int p, min, i, maxLength = 0;;

 

      memset(path, inf, sizeof(int)*(N + 1));

      memset(edges, -1, sizeof(edges));

      path[K] = 0;

 

      for (i = 0; i<times.size(); i++)

      {

            edges[times[i][0]][times[i][1]] =times[i][2];

      }

      int k;

      for (k = 1; k <= N; k++)

      {

            for (min = inf, i = 1; i <= N;i++)

            {

                  if (!vst[i] && path[i]>= 0 && path[i] < min)

                       p = i, min = path[i];

            }

 

            if (min == inf) break;

 

            for (vst[p] = 1, i = 1; i <= N;i++)

                  if (!vst[i] &&edges[p][i] >= 0)

                       if (min + edges[p][i]< path[i])

                             path[i] = min +edges[p][i], prev[i] = p;

      }

 

      if (k != N + 1) return -1;

 

      for (i = 1; i <= N; i++)

      {

            if (path[i] > maxLength)maxLength = path[i];

      }

 

      return maxLength;

       

    }

};