[宽度优先搜索] leetcode 743 Network Delay Time

problem:https://leetcode.com/problems/network-delay-time

        相当于求单源带权最短路径。然后取所有最短路径中最大的那个。

class Solution {
public:
    vector<unordered_map<int, int>> graph;
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        graph.resize(N + 1);
        for (auto& time : times)
        {
            graph[time[0]][time[1]] = time[2];
        }

        vector<int> dist(N + 1, INT_MAX);
        priority_queue<pair<int,int>, vector<pair<int, int>>,greater<pair<int,int>>> pq;
        pq.push({ 0, K });
        dist[K] = 0;
        vector<bool> visit(N + 1, false);
        
        while (!pq.empty())
        {
            int cur = pq.top().second;        
            pq.pop();
            visit[cur] = true;
            for (auto& neighbor : graph[cur])
            {
                int next = neighbor.first;
                int weight = neighbor.second;
                dist[next] = min(dist[next], dist[cur] + weight);
                if (!visit[next])
                {
                    pq.push({ weight, next });
                }
            }
        }
        int res = *max_element(dist.begin() + 1, dist.end());
        return res == INT_MAX ? -1 : res;
    }
};

 

posted @ 2019-08-12 13:27  fish1996  阅读(181)  评论(0编辑  收藏  举报