[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>& times, int N, int K) {
        vector sigTime(N, INT_MAX);
        vector< vector > mat(N, vector(N, -1));    //adjacent matrix
        for(auto edgeVec : times) {
            mat[ edgeVec[0] - 1][ edgeVec[1] - 1] = edgeVec[2];
        }
        K = K - 1;
        sigTime[K] = 0;
        queue nodeQ;
        nodeQ.push(K);
        while(!nodeQ.empty()) {
            int nd = nodeQ.front();
            for(int i=0; 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>& times, int N, int K) {
        vector 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;
    }
};

你可能感兴趣的:(IT公司面试习题,Leetcode,解题报告,BFS,Graph)