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;
    }
}

上一篇:文献阅读报告 - 3DOF Pedestrian Trajectory Prediction


下一篇:Epic Transformation(思维 + 优先队列 + 贪心)