题目
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:
Nwill be in the range[1, 100].Kwill 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 <= Nand1 <= w <= 100.
解题思路
最重要的就是理解题意,题目的意思是:当信号到达了一个结点时,在下一刻可以同时转发给该结点相邻的所有结点,求传送到每一个结点的最终时间。这样,问题就变成了求解从结点 K 到所有结点的单源最短路问题,然后,从中选择最长的一条路所用的时间即为答案。因此本题使用 Dijkstra 算法进行求解。需要注意的是每次从所有的路径中选择最短路径的结点出来后,要将该结点设置为已访问,避免再重复访问。
C++代码实现
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<vector<int> > graph(N + 1, vector<int>(N + 1, 60001));
vector<int> cost(N + 1);
vector<bool> visited(N + 1, false);
for (int i = 0; i < times.size(); ++i) { graph[times[i][0]][times[i][1]] = times[i][2]; }
for (int i = 1; i <= N; ++i) { cost[i] = graph[K][i]; }
cost[K] = 0;
visited[K] = true;
for (int i = 1; i <= N; ++i) {
int minNode = findMinNode(cost, visited);
if (minNode == 0) { break; }
for (int j = 1; j <= N; ++j) {
if (!visited[j] && cost[j] > cost[minNode] + graph[minNode][j]) {
cost[j] = cost[minNode] + graph[minNode][j];
}
}
visited[minNode] = true;
}
return calSum(cost);
}
int findMinNode(vector<int>& cost, vector<bool>& visited) {
int minIndex = 0, minV = 60001;
for (int i = 1; i < cost.size(); ++i) {
if (!visited[i] && minV > cost[i]) {
minIndex = i;
minV = cost[i];
}
}
return minIndex;
}
int calSum(vector<int>& cost) {
int sum = 0;
for (int i = 1; i < cost.size(); ++i) {
if (cost[i] == 60001) { return -1; }
if (sum < cost[i]) { sum = cost[i]; }
}
return sum;
}
};
本文解析了一道关于网络节点信号传播的问题,通过Dijkstra算法求解单源最短路径问题,进而找出信号从指定节点传播到所有节点所需的最大时间。
1327

被折叠的 条评论
为什么被折叠?



