前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 62:743. Network Delay Time

LWC 62:743. Network Delay Time

作者头像
用户1147447
发布2018-01-02 10:41:54
6660
发布2018-01-02 10:41:54
举报
文章被收录于专栏:机器学习入门

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版:

代码语言:javascript
复制
    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算法,代码如下:

代码语言:javascript
复制
     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版:

代码语言:javascript
复制
    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 版:

代码语言:javascript
复制
    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,哈哈!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-12-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 62:743. Network Delay Time
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档