题目描述:
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:
1. N will be in the range [1, 100].
2. K will be in the range [1, N].
3. The length of times will be in the range [1, 6000].
4. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
int result=0;
vector<vector<int>> edge(N+1,vector<int>(N+1,-1));
for(auto time:times) edge[time[0]][time[1]]=time[2];
vector<int> distance(N+1,INT_MAX);
queue<int> q;
q.push(K);
distance[K]=0;
while(!q.empty())
{
int n=q.size();
for(int i=0;i<n;i++)
{
int u=q.front();
q.pop();
for(int v=1;v<=N;v++) // 寻找从u->v的边
{
if(edge[u][v]!=-1)
{
// 用距离关系来判断是否要访问一个节点,避免重复遍历,而不是用哈希表
// 从u->v的路径可以更新distance[v],那么v应该加入队列中,从而可以更新它的领接点
if (distance[v]>distance[u]+edge[u][v])
{
q.push(v);
distance[v]=min(distance[v],distance[u]+edge[u][v]);
}
}
}
}
}
for (int i=1;i<=N;i++) result=max(result,distance[i]);
if(result==INT_MAX) return -1;
else return result;
}
};