LeetCode練習題743. Network Delay Time
阿新 • • 發佈:2018-12-14
題目
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 have1 <= u, v <= N
and1 <= w <= 100
.
分析
這道題可以簡化為有向圖求某一點到其餘點最短路徑的問題,因為網路傳播時,訊號向所有方向傳播,某節點收到訊號時,該訊號一定是經過最短的路徑到達的。若從起始點出發,存在一點與起始點不連通,則返回-1,否則返回起始點到其餘點最短路徑中的最大值。
因為題目中邊的權都是正數,所以這裡使用Dijkstra演算法,大概思路如下:
- 一開始設定從起始點到其餘點 i 的最短路徑 dist[i] 為 INT_MAX
- 以寬度優先演算法遍歷有向圖,遍歷到的節點 u ,檢視與 u 相連的所有節點 v,若 dist[u] + l(u,v) < dist[v],則令dist[v] = dist[u] + l(u,v)。
- 最後檢查所有節點 i 的 dist[i],若存在 dist[i] 為 INT_MAX,說明有節點與初始點不連通,返回 -1,否則返回 dist[i] 中的最大值。
程式碼
class Solution { public: int networkDelayTime(vector<vector<int>>& times, int N, int K) { int dist[101]; bool found[101]; vector<int> que; int temp; int max = 0; int len = times.size(); for (int i = 0; i < 101; i++) { dist[i] = INT_MAX; found[i] = false; } dist[K] = 0; found[K] = true; que.push_back(K); while (que.size()) { temp = que.front(); que.erase(que.begin()); for (int i = 0; i < len; i++) { if (times[i][0] == temp) { if (dist[temp] + times[i][2] < dist[times[i][1]]) { dist[times[i][1]] = dist[temp] + times[i][2]; found[times[i][1]] = true; que.push_back(times[i][1]); } } } } for (int i = 1; i <= N; i++) { if (found[i] == false) { return -1; } } for (int i = 1; i <= N; i++) { max = dist[i] > max ? dist[i] : max; } return max; } };