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:
Nwill be in the range[1, 100].Kwill be in the range[1, N].- The length of
timeswill be in the range[1, 6000]. - All edges
times[i] = (u, v, w)will have1 <= u, v <= Nand1 <= 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;
}
};
本文介绍了一个算法问题:如何计算从特定节点发出信号后所有节点接收该信号所需的最长时间。通过BFS实现,确保只更新更优的时间记录,并利用map记录每个节点的最短到达时间。
6148

被折叠的 条评论
为什么被折叠?



