Code & Func
2019-12-16

第40天。

今天的题目是Network Delay Time:

一道图的题目,比较常规,用Dijkstra求单源最短路,然后取距离最远的那个即可得到Network Delay Time:

1
int minDisNode(vector<bool> &visited, vector<int> &dis) {
2
int min_v = INT_MAX, min_i = -1;;
3
for(int j = 0;j < dis.size();j++) {
4
if (!visited[j] && dis[j] < min_v) {
5
min_v = dis[j];
6
min_i = j;
7
}
8
}
9
return min_i;
10
}
11
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
12
if (times.size() == 0 || N==0 || K <= 0) return -1;
13
//build graph;
14
vector<vector<int>> graph(N, vector<int>(N, INT_MAX));
15
for(auto &t: times) {
32 collapsed lines
16
graph[t[0]-1][t[1]-1] = t[2];
17
}
18
19
K--;
20
vector<int> dis(N, INT_MAX);
21
vector<bool> visited(N, false);
22
visited[K] = true;
23
for(int i = 0;i < dis.size(); i++) {
24
dis[i] = graph[K][i];
25
}
26
dis[K] = 0;
27
28
for(int i = 1;i < N; i++) {
29
// find a unvisited node which dis is min
30
int j = minDisNode(visited, dis);
31
if (j == -1) return -1;
32
33
visited[j] = true;
34
for(int k = 0;k < dis.size(); k++) {
35
if (graph[j][k] != INT_MAX) {
36
dis[k] = min(dis[k], dis[j] + graph[j][k]);
37
}
38
}
39
}
40
41
int res = 0;
42
for(int i = 0;i < N;i++) {
43
if (dis[i] != INT_MAX)
44
res = max(res, dis[i]);
45
}
46
return res;
47
}
上一条动态