LeetCode #743 Network Delay Time
2017-12-24 00:52
447 查看
题目
There areNnetwork nodes, labelled
1to
N.
Given
times, a list of travel times as directed edges
times[i] = (u, v, w), where
uis the source node,
vis 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 have
1 <= u, v <= Nand
1 <= 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; } };
相关文章推荐
- leetcode743——Network Delay Time
- Leetcode算法学习日志-743 Network Delay Time
- leetcode练习 Network Delay Time
- [LeetCode] Network Delay Time 网络延迟时间
- 743-Network Delay Time
- Network Delay Time - LeetCode
- Leetcode-Network Delay Time
- Network Delay Time
- 算法练习(43):Network Delay Time
- Leetcode算法题——Network Delay Time
- Network Delay Time问题及解法
- Network Delay Time
- LeetCode Best Time to Buy and Sell Stock
- leetcode 714 Best Time to Buy and Sell Stock with Transaction Fee
- LeetCode: Best Time to Buy and Sell Stock
- sql server 中延迟时间的方法 waitfor delay / time
- 【Leetcode】Best Time to Buy and Sell Stock II
- 【Leetcode】Best Time to Buy and Sell Stock
- ***Leetcode 188. Best Time to Buy and Sell Stock IV | dp
- 122.[LeetCode]Best Time ti Buy and Shell stock II