Code & Fun

第40天。

今天的题目是Network Delay Time:

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

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

K--;
vector<int> dis(N, INT_MAX);
vector<bool> visited(N, false);
visited[K] = true;
for(int i = 0;i < dis.size(); i++) {
dis[i] = graph[K][i];
}
dis[K] = 0;

for(int i = 1;i < N; i++) {
// find a unvisited node which dis is min
int j = minDisNode(visited, dis);
if (j == -1) return -1;

visited[j] = true;
for(int k = 0;k < dis.size(); k++) {
if (graph[j][k] != INT_MAX) {
dis[k] = min(dis[k], dis[j] + graph[j][k]);
}
}
}

int res = 0;
for(int i = 0;i < N;i++) {
if (dis[i] != INT_MAX)
res = max(res, dis[i]);
}
return res;
}

本文首发于Code & Fun