LWC 62:743. Network Delay Time

LWC 62:743. Network Delay Time

传送门:743. Network Delay Time

Problem:

There are N network nodes, labelled 1 to N. 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.

Note:

N will be in the range [1, 100].

K will be in the range [1, N].

The length of times will be in the range [1, 6000].

All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

思路: 求从某个结点k出发到任意结点的距离,在这些距离中找最大值即可。实际上该题是求解任意两个结点之间的最短路径,先采用Dijkstra算法实现一波。最短路径的相关知识可以参考【挑战程序竞赛系列(11):2.5最短路径

Java版:

    class Edge{
        int from;
        int to;
        int weight;

        Edge(int from, int to, int weight){
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
    }

    class Node implements Comparable<Node>{

        int v;
        int dist;

        Node(int v, int dist){
            this.v = v;
            this.dist = dist;
        }

        @Override
        public int compareTo(Node that) {
            return this.dist - that.dist;
        }
    }

    public int networkDelayTime(int[][] times, int N, int K) {

        int n = times.length;
        List<Edge>[] graph = new ArrayList[N];

        for (int i = 0; i < N; ++i) {
            graph[i] = new ArrayList<>();
        }

        for (int i = 0; i < n; ++i) {
            int from   = times[i][0];
            int to     = times[i][1];
            int weight = times[i][2];
            from --;
            to --;
            graph[from].add(new Edge(from, to, weight));
        }

        int ans = 0;
        boolean[] vis = new boolean[N];

        Queue<Node> queue = new PriorityQueue<>();
        queue.offer(new Node(K - 1, 0));

        int[] dist = new int[N];
        Arrays.fill(dist, 0x3f3f3f3f);

        while (!queue.isEmpty()) {
            Node now = queue.poll();
            for (Edge e : graph[now.v]) {
                if (!vis[e.from]) {
                    Node nxt = new Node(e.to, now.dist + e.weight);
                    dist[e.to] = Math.min(dist[e.to], nxt.dist);
                    queue.offer(nxt);
                }
            }
            vis[now.v] = true;
        }

        for (int i = 0; i < N; ++i) {
            if (i == K - 1) continue;
            ans = Math.max(ans, dist[i]);
        }


        return ans >= 0x3f3f3f3f ? -1 : ans;
    }

当然计算任意结点之间的最短距离可以采用warshallFloyd算法,代码如下:

     public int networkDelayTime(int[][] times, int N, int K) {
         int INF = 0x3f3f3f3f;
         int[][] dist = new int[N][N];

         for (int i = 0; i < N; ++i) {
             for (int j = 0; j < N; ++j) {
                 dist[i][j] = INF;
             }
         }

         for (int[] time : times) {
             int from = time[0];
             int to   = time[1];
             int cost = time[2];
             from --;
             to --;
             dist[from][to] = cost;
         }

         for (int k = 0; k < N; ++k) {
             for (int i = 0; i < N; ++i) {
                 for (int j = 0; j < N; ++j) {
                     dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
                 }
             }
         }

         int ans = 0;
         for (int i = 0; i < N; ++i) {
             if (i ==  K - 1) continue;
             ans = Math.max(ans, dist[K - 1][i]);
         }

         return ans >= INF ? -1 : ans;
     }

warshallFloyd算法的正确性详见知乎高票回答【Floyd算法为什么把k放在最外层?

Python版:

    def networkDelayTime(self, times, N, K):
        """
        :type times: List[List[int]]
        :type N: int
        :type K: int
        :rtype: int
        """
        INF = 0x3f3f3f3f
        dist = [[INF] * N for _ in range(N)]

        for time in times:
            u = time[0]
            v = time[1]
            w = time[2]
            dist[u - 1][v - 1] = w

        for k in xrange(N):
            for i in xrange(N):
                for j in xrange(N):
                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

        ans = 0
        for i in range(N):
            if (i == K - 1): continue
            else:
                ans = max(ans, dist[K - 1][i])

        return -1 if ans >= INF else ans

Python Dijkstra 版:

    def networkDelayTime(self, times, N, K):
        import heapq

        """
        :type times: List[List[int]]
        :type N: int
        :type K: int
        :rtype: int
        """
        pq = []
        INF = float('inf')
        dist = [INF] * N

        graph = [[] for _ in range(N)]

        for time in times:
            graph[time[0] - 1].append((time[1] - 1, time[2]))

        heapq.heappush(pq, (0, K - 1))
        dist[K - 1] = 0

        while len(pq):
            cur = heapq.heappop(pq)
            for to, cost in graph[cur[1]]:
                if (dist[to] > dist[cur[1]] + cost):
                    dist[to] = cost + dist[cur[1]]
                    heapq.heappush(pq, (dist[to], to))

        ans = 0
        for i in range(N):
            if i == K - 1:
                continue
            else:
                ans = max(ans, dist[i])

        return -1 if ans >= INF else ans

知道为什么Dijkstra没有发明warshallFloyd么?因为他的名字是D”ijk”stra而不是D”kij”stra,哈哈!

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏赵俊的Java专栏

平衡二叉树

1635
来自专栏King_3的技术专栏

leetcode-643-Maximum Average Subarray I

932
来自专栏计算机视觉与深度学习基础

Leetcode 135 Candy

There are N children standing in a line. Each child is assigned a rating value....

19210
来自专栏King_3的技术专栏

leetcode-137-Single Number II-第一种解法

2193
来自专栏计算机视觉与深度学习基础

Leetcode 84 Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the...

1679
来自专栏King_3的技术专栏

leetcode-69-Sqrt(x)

2474
来自专栏书山有路勤为径

二叉树层次遍历

二叉树层次遍历,又称为宽度优先搜索,按树的层次依次访问树的结点。层次遍历使用队列对遍历节点进行 存储,先进入队列的结点, 优先遍历拓展其左孩子与 右孩子。

431
来自专栏数据结构与算法

对称二叉树

对称二叉树 【问题描述】     如果二叉树的左右子树的结构是对称的,即两棵子树皆为空,或者皆不空,则称该二叉树是对称的。编程判断给定的二叉树是否对称.    ...

3234
来自专栏程序生活

二叉树的深度

题目描述 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 代码实现 递归实现 # ...

2364
来自专栏机器学习入门

LWC 51:683. K Empty Slots

LWC 51:683. K Empty Slots 传送门:683. K Empty Slots Problem: There is a garden wit...

2088

扫码关注云+社区