There are N
network nodes, labelled 1
to N
.html
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.node
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:spa
N
will be in the range [1, 100]
.K
will be in the range [1, N]
.times
will be in the range [1, 6000]
.times[i] = (u, v, w)
will have 1 <= u, v <= N
and 0 <= w <= 100
.
這道題說的就是給了咱們一些有向邊,又給了一個結點K,問至少須要多少時間才能從K到達任何一個結點。實際上是一個求帶權的有向圖的最短路的的問題,因爲帶權,因此BFS不能用,咱們能夠用Dijkstra算法、FLoyd算法以及Bellman-Ford算法。參考連接:http://www.cnblogs.com/grandyang/p/8278115.htmlcode
這個題中我用Dijkstra算法,其實,Dijkstra算法有比較固定的模板,本質是利用貪心的。Dijkstra算法因爲貪心的性質,因此只能解決權都爲正的有向圖的最短路的問題。htm
普通的Dijkstra算法的時間複雜度爲O(V2)。blog
C++代碼:隊列
int INF = 0x3f3f3f3f; class Solution { public: int networkDelayTime(vector<vector<int>>& times, int N, int K) { int mp[N+1][N+1]; int dis[N+1]; int book[N+1]; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ mp[i][j] = INF; } } int len = times.size(); for(int i = 1;i <= len; i++){ int w = times[i-1][2]; int u = times[i-1][0]; int v = times[i-1][1]; if(w < mp[u][v]){ mp[u][v] = w; } } for(int i = 1; i <= N; i++){ dis[i] = mp[K][i]; book[i] = 0; } dis[K] = 0; book[K] = 1; for(int i = 1; i <= N; i++){ int minn = INF,t = K; for(int j = 1; j <= N; j++){ if(book[j] == 0 && dis[j] < minn){ minn = dis[j]; t = j; } } book[t] = 1; for(int j = 1; j <= N; j++){ if(book[j] == 0 && dis[t] + mp[t][j] < dis[j] && mp[t][j] < INF){ dis[j] = dis[t] + mp[t][j]; } } } int sum = 0; for(int i = 1; i <= N; i++){ sum = max(sum,dis[i]); } if(sum == INF) return -1; return sum; } };
若是是基於優先隊列的實現方法的話,時間複雜度就是O(E + VlogV)。get