743. Network Delay Time [Dijkstra]

查看题目

经典Dijkstra算法

typedef pair<int, int> intint;
const int INF = 10000; //100*100, N和w最大值均为100

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<intint > vw[N+1];
        //存入u节点所能到的边及权重
        for (auto item : times) {
            vw[item[0]].push_back({item[1],item[2]});
        }
        //初始化各节点到源节点的距离为无穷
        vector<int> dis(N + 1, INF);
        dis[K] = 0;
        //优先队列用来选择下一个要访问的节点
        priority_queue<intint, vector<intint >, greater<intint > > pq;
        pq.push({0, K});
        
        while (!pq.empty()) {
            intint dv = pq.top();
            pq.pop();
            int u = dv.second, disu = dv.first;
            //遍历此节点所能到达的节点
            for (auto item : vw[u]) {
                int w = item.second, v = item.first;
                //若通过此边使得v节点到源节点的距离更小,更新dis值
                if (dis[v] > disu+w) {
                    dis[v] = disu+w;
                    pq.push({dis[v], v});
                }
            }
        }
        
        int rtn = *max_element(dis.begin()+1, dis.end());
        return (rtn == INF) ? -1 : rtn; 
        
    }
};

未避免将同一节点多次压入队列中,因为此节点到源节点的最短距离总会排在前面,从而第一个从队列中压出,而再次压出此节点时,不会影响到dis值

你可能感兴趣的:(Leetcode)