其他分享
首页 > 其他分享> > 743. Network Delay Time[Medium](Leetcode每日一题-2021.08.02)

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:

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>> &times, 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;
    }
};

标签:02,743,dist,Network,int,signal,times,vector,ui
来源: https://blog.csdn.net/sjt091110317/article/details/119335766