743. Network
Delay Time
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
.
1、BFS。如果到一个点,发现接下去要找的点到达的时间比之前到过的时间要短,才push进queue。不然没有意义。
2、map存到达时间。也可以当做bfs的hash表使用。
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K)
{
int ret = INT_MIN;
map<int, vector<pair<int, int> > > route; //pair 存的是 终点-时间
for (int i = 0; i < times.size(); i ++)
{
route[times[i][0]].push_back(make_pair(times[i][1], times[i][2]));
}
map<int, int> arrive_time; //到达i点的最快时间。也可以当做hash表存已经遍历过的点
arrive_time[K] = 0;
queue<int> que;
que.push(K);
while (!que.empty())
{
int top = que.front();
que.pop();
for (int i = 0; i < route[top].size(); i++)
{
if (arrive_time.find(route[top][i].first) == arrive_time.end() ||
arrive_time[route[top][i].first] > arrive_time[top] + route[top][i].second
) //第一次遍历 或 当前这个路径的时间更少,那就更新
{
arrive_time[route[top][i].first] = arrive_time[top] + route[top][i].second;
que.push(route[top][i].first);
}
}
}
if (arrive_time.size() != N)
return -1;
for (auto it : arrive_time)
ret = max(ret, it.second);
return ret;
}
};