1. 程式人生 > 實用技巧 >[LeetCode] 743. Network Delay Time

[LeetCode] 743. Network Delay Time

There areNnetwork nodes, labelled1toN.

Giventimes, a list of travel times asdirectededgestimes[i] = (u, v, w), whereuis the source node,vis the target node, andwis the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain nodeK. 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

Note:

  1. Nwill be in the range[1, 100].
  2. Kwill be in the range[1, N].
  3. The length oftimeswill be in the range[1, 6000].
  4. All edgestimes[i] = (u, v, w)will have1 <= u, v <= Nand0 <= w <= 100.

網路延遲時間。

有N個網路節點,標記為1到N。

給定一個列表times,表示訊號經過有向邊的傳遞時間。times[i] = (u, v, w),其中u是源節點,v是目標節點, w是一個訊號從源節點傳遞到目標節點的時間。

現在,我們從某個節點K發出一個訊號。需要多久才能使所有節點都收到訊號?如果不能使所有節點收到訊號,返回-1。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/network-delay-time
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

題意是從節點K出發,問需要多久才能讓所有節點都接收到訊號。很顯然這是個圖論graph的題,那麼我們首先要做的就是把圖建立起來。這裡因為input裡給了三個引數,u,v和w,表示的是每條邊的起點,終點和權重。所以我這裡建立一個hashmap<u, hashmap<v, weight>>。同時既然是問需要多少時間才能讓訊號傳給所有節點,那麼這裡我們自然會選擇代價最小的結果

,所以我們應該是需要一個priority queue來存放每兩個點之間的weight的。最後我們需要一個boolean陣列記錄每個節點是否訪問過。把圖建立好之後,我們把起始點K和他的權重0放入pq(因為從K點出發到K點,是沒有花費的)。

當pq不為空的時候,我們從pq中poll一個元素出來,並把它標記為visited,此時我們還需要用for loop遍歷這個節點所有的鄰居節點next,並把走到下一個節點next的代價累加到當前的代價curDistance上,再放回pq繼續迴圈。停止迴圈的條件是pq為空或者所有節點都遍歷完了。此時判斷節點是否都遍歷到了,若是則返回代價res;否則返回-1,說明有節點是怎麼樣都無法從K出發訪問到的。

時間O(V + E)

空間O(V + E)

Java實現

 1 class Solution {
 2     public int networkDelayTime(int[][] times, int N, int K) {
 3         HashMap<Integer, HashMap<Integer, Integer>> g = new HashMap<>();
 4         for (int[] t : times) {
 5             g.putIfAbsent(t[0], new HashMap<>());
 6             g.get(t[0]).put(t[1], t[2]);
 7         }
 8 
 9         // distance, v
10         PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
11         pq.offer(new int[] { 0, K });
12         boolean[] visited = new boolean[N + 1];
13         int res = 0;
14         while (!pq.isEmpty()) {
15             int[] cur = pq.poll();
16             int curDistance = cur[0];
17             int curNode = cur[1];
18             if (visited[curNode] == true) {
19                 continue;
20             }
21             visited[curNode] = true;
22             res = curDistance;
23             N--;
24             if (N == 0) {
25                 break;
26             }
27             if (g.containsKey(curNode)) {
28                 for (int next : g.get(curNode).keySet()) {
29                     pq.offer(new int[] { curDistance + g.get(curNode).get(next), next });
30                 }
31             }
32         }
33         return N == 0 ? res : -1;
34     }
35 }

LeetCode 題目總結