743. Network Delay Time

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:

  1. N will be in the range [1, 100].
  2. K will be in the range [1, N].
  3. The length of times will be in the range [1, 6000].
  4. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

题意:从source出发,求出source到所有节点路径的最小值,若有节点无法到达则返回-1

M1: Dijkstra's algorithm

Time: O(N^2) if using adjacency matrix, O(NlogN + E) if using heap, Space: O(N + E)

用Map<Integer, Map<Integer, Integer>>存图的信息,min heap存(time, node),还需要一个visited数组和time数组(每个点到K所需的最小时间)。从K开始,首先把K放进min heap。当heap不为空时,poll出堆顶元素(最小时间),如果没有访问过,标记visited为true,N减1,更新res为当前最短时间,如果graph包含当前node的信息,遍历该node的所有neighbor,如果这个neighbor没有被访问过,并且当前时间(K到该node的最短时间)+ 此neighbor到当前node的时间比time数组里的K到这个neighbor的时间少,更新time[nei],并将这个neighbor的信息(time, node)放入min heap。当heap为空时退出循环。如果最后N不为0,说明有元素无法到达,返回-1,否则返回res。

class Solution {
    public int networkDelayTime(int[][] times, int N, int K) {
        int res = 0;
        Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        boolean[] visited = new boolean[N+1];
        int[] time = new int[N+1];
        Arrays.fill(time, Integer.MAX_VALUE);
        time[K] = 0;
        
        for(int[] t : times) {
            graph.putIfAbsent(t[0], new HashMap<>());
            graph.get(t[0]).put(t[1], t[2]);
        }
        
        minHeap.add(new int[] {0, K});
        
        while(!minHeap.isEmpty()) {
            int[] cur = minHeap.poll();
            int t = cur[0], node = cur[1];
            if(visited[node]) continue;
            visited[node] = true;
            res = t;
            N--;
            if (!graph.containsKey(node)) continue;
            for(int nei : graph.get(node).keySet()) {
                if(!visited[nei] && t + graph.get(node).get(nei) < time[nei]) {
                    time[nei] = t + graph.get(node).get(nei);
                    minHeap.add(new int[] {time[nei], nei});
                }
            }
        }
        return N == 0 ? res : -1;
    }
}

M2: Bellman-Ford

Time: , Space: O(N)

M3: Floyd-Warshall (all pairs)

Time: O(N^3), Space: O(N^2)

可以求任意两点间的路径

原文地址:https://www.cnblogs.com/fatttcat/p/10012471.html