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算法

posted @ 2020-09-10 13:54  zmachine  阅读(164)  评论(0编辑  收藏  举报