743. Network Delay Time[Medium](Leetcode每日一题-2021.08.02)
2021/8/2 23:08:58
本文主要是介绍743. Network Delay Time[Medium](Leetcode每日一题-2021.08.02),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Problem
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Constraints:
- 1 <= k <= n <= 100
- 1 <= times.length <= 6000
- times[i].length == 3
- 1 <= ui, vi <= n
- ui != vi
- 0 <= wi <= 100
- All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
Example1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Example2
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Example3
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Solution
class Solution { public: int networkDelayTime(vector<vector<int>> ×, int n, int k) { const int inf = INT_MAX / 2; // 邻接矩阵存储边信息 vector<vector<int>> g(n, vector<int>(n, inf)); for (auto &t : times) { // 边序号从 0 开始 int x = t[0] - 1, y = t[1] - 1; g[x][y] = t[2]; } // 从源点到某点的距离数组 vector<int> dist(n, inf); // 由于从 k 开始,所以该点距离设为 0,也即源点 dist[k - 1] = 0; // 节点是否被更新数组 vector<bool> used(n); for (int i = 0; i < n; ++i) { // 在还未确定最短路的点中,寻找距离最小的点 int x = -1; for (int y = 0; y < n; ++y) { if (!used[y] && (x == -1 || dist[y] < dist[x])) { x = y; } } // 用该点更新所有其他点的距离 used[x] = true; for (int y = 0; y < n; ++y) { dist[y] = min(dist[y], dist[x] + g[x][y]); } } // 找到距离最远的点 int ans = *max_element(dist.begin(), dist.end()); return ans == inf ? -1 : ans; } };
这篇关于743. Network Delay Time[Medium](Leetcode每日一题-2021.08.02)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-30uniAPP 实现全屏左右滚动滚动的效果-icode9专业技术文章分享
- 2024-06-30如何在本地使用授权或插件-icode9专业技术文章分享
- 2024-06-30伪静态规则配置方法汇总-icode9专业技术文章分享
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding