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
.
给定一个有向图,权值是时间,问从给定节点走遍其他所有节点花费的时间
使用Dijkstra算法,找到给定点到其他所有节点的时间代价,最长的就是答案。注意在存储有向图时,需要注意,可能会给同一条边多次赋值,需要存储最小的。
Dijkstra简介:每一次找到没有走到的最近的节点,并使用这一节点更新到其他没有走到的节点的距离
class Solution {
public int networkDelayTime(int[][] times, int N, int K) {
int[][] distance = new int[N + 1][N + 1];
for(int[] it : distance)
Arrays.fill(it, 99999999);
for(int[] it : times){
int i = it[0], j = it[1];
int temp = Math.min(distance[i][j], it[2]);
distance[i][j] = temp;
}
for(int i = 1; i < N + 1; i++)
distance[i][i] = 0;
boolean[] visited = new boolean[N + 1];
for(int ct = 0; ct < N; ct++){
int min = -1;
for(int i = 1; i < N + 1; i++){
if(visited[i])
continue;
if(min == -1 || distance[K][i] < distance[K][min])
min = i;
}
if(distance[K][min] == 99999999)
break;
visited[min] = true;
for(int i = 1; i < N + 1; i++){
if(!visited[i] && distance[K][min] + distance[min][i] < distance[K][i]){
distance[K][i] = distance[K][min] + distance[min][i];
}
}
}
int ans = 0;
distance[K][0] = 0;
for(int it : distance[K]){
ans = Math.max(ans, it);
//System.out.print(it + " ");
}
return ans == 99999999 ? -1 : ans;
}
}