LeetCode 图篇

743. 网络延迟时间

有 N 个网络节点,标记为 1 到 N。

给定一个列表 times,表示信号经过有向边的传递时间。 times[i] = (u, v, w),其中 u 是源节点,v 是目标节点, w 是一个信号从源节点传递到目标节点的时间。

现在,我们从某个节点 K 发出一个信号。需要多久才能使所有节点都收到信号?如果不能使所有节点收到信号,返回 -1。

示例:

输入:times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
输出:2

注意:

N 的范围在 [1, 100] 之间。
K 的范围在 [1, N] 之间。
times 的长度在 [1, 6000] 之间。
所有的边 times[i] = (u, v, w) 都有 1 <= u, v <= N 且 0 <= w <= 100。

solution 1(Dijkstra算法)

    public int networkDelayTime(int[][] times, int N, int K) {
        //整理图为散列表
        Map<Integer,List<int[]>> graph = new HashMap();
        for(int[] row:times){
            if (!graph.containsKey(row[0])) {
                graph.put(row[0],new ArrayList<int[]>());
            }
            graph.get(row[0]).add(new int[]{row[1],row[2]});
        }
        //初始化保存起点到每一个的距离的数组 和 已遍历点的保存
        int[] dist = new int[N+1];
        boolean[] isread = new boolean[N+1];
        Arrays.fill(dist,0x3f3f3f3f);
        dist[0] = K; dist[K] = 0;
        //用最小堆对要处理的点进行排序
        PriorityQueue<Integer> queue = new PriorityQueue<>(
                (point1,point2) -> dist[point1] - dist[point2]);
        queue.offer(K);
        //遍历 处理每一个点,修改到每一个点的最小距离
        while(!queue.isEmpty()){
            Integer curr = queue.poll();
            if (isread[curr]) continue;
            isread[curr] = true;
            //遍历处理点的边到的第二个点
            List<int[]> list = graph.getOrDefault(curr, Collections.emptyList());
            for(int[] currEdge: list){
                int next = currEdge[0];
                if(isread[next]) continue;
                dist[next] = Math.min(dist[next],dist[curr]+currEdge[1]);
                queue.offer(next);
            }
        }
        //遍历距离数组取结果
        int max = Arrays.stream(dist).max().getAsInt();
        return max == 0x3f3f3f3f ? -1: max;
    }
}

posted @ 2020-08-11 22:17  gg12138  阅读(202)  评论(0编辑  收藏  举报