LeetCode #743 Network Delay Time
来源:互联网 发布:网络带给我们的好处 编辑:程序博客网 时间:2024/06/06 04:44
题目
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:
N
will be in the range[1, 100]
.K
will 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 <= N
and1 <= 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; }};
阅读全文
0 0
- LeetCode #743 Network Delay Time
- Leetcode 743. Network Delay Time
- Leetcode算法题——Network Delay Time
- LeetCode | 743. Network Delay Time | 中等难度 图论 单源最短路径题
- LWC 62:743. Network Delay Time
- Network Delay Time问题及解法
- C++ Time Delay
- Max Time-Delay Neural Networks
- Max Time-Delay Neural Networks
- mt2523 How to delay some time
- NTP(Network Time Protocol)
- Network Time Protocol
- Delay
- delay
- delay
- 阅读报告:Congestion Control for High Bandwidth-Delay Product Network
- Emergence、Cascading effect and Delay in network system
- sql server 中延迟时间的方法 waitfor delay / time
- c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)
- java 开发模式之七 : 适配器模式
- LEDE SAMBA
- 佛爷芸: 机器学习算法原理总结系列---算法基础之(1)机器学习介绍
- 2.尾部的零
- LeetCode #743 Network Delay Time
- 集合总结,NIO总结
- nikto使用方法笔记
- 基于jquery模板实现页面渲染
- 数据结构实验之排序四:寻找大富翁
- 数据库查询
- POJ 1451(0ms)(dnf)(树的灵活建立)
- MySQL —— 目录结构和语句规范
- 数据结构实验之查找七:线性之哈希表