其他分享
首页 > 其他分享> > leetcode 743 (Dijkstra Algorithm)

leetcode 743 (Dijkstra Algorithm)

作者:互联网

Solution for leetcode 743

class Solution {
    public int networkDelayTime(int[][] times, int n, int k) {
        Map<Integer, ArrayList<int[]>> map = new HashMap();
        for(int i = 0; i < times.length; i++){
            int from = times[i][0];
            ArrayList<int[]> cur = map.getOrDefault(from,new ArrayList());
            cur.add(new int[]{times[i][1], times[i][2]});
            map.put(from, cur);
        }
        int[] distance = new int[n + 1];
        boolean[] visited = new boolean[n + 1];
        Arrays.fill(distance, Integer.MAX_VALUE);
        PriorityQueue<Integer> pq = new PriorityQueue<>((o1,o2) -> distance[o1] - distance[o2]);
        pq.offer(k);
        distance[k] = 0;
        distance[0] = 0;
        while(!pq.isEmpty()){
            int cur = pq.poll();
            if(visited[cur]){
                continue;
            }
            visited[cur] = true;
            List<int[]> list = map.getOrDefault(cur, new ArrayList());
            for(int[] arr : list){
                int next = arr[0];
                int dis = distance[cur] + arr[1];
                distance[next] = Math.min(dis , distance[next]);
                pq.offer(next);
                
            } 
        }
        int output = Integer.MIN_VALUE;
        for(int i = 0; i < n + 1; i++){
            output = Math.max(output, distance[i]); 
        }
        return output == Integer.MAX_VALUE ? -1 : output;
    }
}

标签:distance,743,cur,int,Dijkstra,pq,output,new,leetcode
来源: https://blog.csdn.net/weixin_41917137/article/details/118367655