Network Delay Time

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.

Example 1:

Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

思路:network delay time 跟 Cheapest Flights Within K Stops 一模一样,都是dijkstra算法;其实这个题是在算arrive最后一个node的最大时间,其实也是最小的时间,因为arrive每个点,我们每次都是用最小的time去算的,只是最后结果,我们要最后arrive那个点的时间。注意,这里需要判断一下graph.get(node.id)是否为空;这个很重要;

class Solution {
    public class Node {
        int id;
        int time;
        public Node(int id, int time) {
            this.id = id;
            this.time = time;
        }
    }
    
    public int networkDelayTime(int[][] times, int n, int k) {
        HashMap<Integer, HashMap<Integer, Integer>> graph = new HashMap<>();
        for(int[] time: times) {
            int u = time[0];
            int v = time[1];
            int w = time[2];
            graph.putIfAbsent(u, new HashMap<>());
            graph.get(u).put(v, w);
        }
        
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) ->(a.time - b.time));
        pq.offer(new Node(k, 0));
        int maxtime = 0;
        HashSet<Integer> visited = new HashSet<>();
        
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            if(visited.contains(node.id)) {
                continue;
            }
            visited.add(node.id);
            maxtime = Math.max(maxtime, node.time);
            if(graph.get(node.id) != null) {
                for(Integer neighbor: graph.get(node.id).keySet()) {
                    pq.offer(new Node(neighbor, node.time + graph.get(node.id).get(neighbor)));
                }
            }
        }
        return visited.size() == n ? maxtime : -1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值