1. 程式人生 > 實用技巧 >Network Delay Time

Network Delay Time

here 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

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        const int INF = 0x3f3f3f3f;
        vector<vector<int>> g(N+1,vector<int>(N+1,INF));
        for(auto&v: times){
            g[v[0]][v[1]] = v[2];
        }
        vector
<int> dist(N+1,INF);//距離起始點的最短距離 vector<bool> st(N+1,false);//是否已經取得了最優解 dist[K] =0;//起始點 for(int i=0;i< N-1;i++){ int t=-1; for(int j=1;j<=N;j++){//在還未確定最短路徑的點中,尋找到起始點距離最小的點 if(!st[j] && (t==-1 || dist[t] > dist[j])){//找出當前節點出發的最短路徑
t=j; } } st[t] = true;//t號的最短路徑已經確定 for(int j=1;j<=N;++j){//用t更新其他點的距離 dist[j] = min(dist[j],dist[t]+g[t][j]); } } int ans = *max_element(dist.begin()+1,dist.end()); return ans == INF ? -1:ans; } };

注意:

樸素Dijkstra演算法