题目
网址直达
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 have 1 <= u, v <= N and 0 <= w <= 100.
思路
这是一个路径搜索题,目标是要到达所有的结点并返回最小的时间;如果不能到达所有的结点就返回-1。
输入的数组times表示结点之间的连接关系,可以定义一个新的二维connect数组,connect[i][j]表示第i个结点到第j个结点的时间,由于时间是可以为0的,所以需要初始化为-1表示没有连接,否则就是有连接。
此外,还需要一个布尔数组receive,用来记录这个点是否已接收到信号,初始值是false,不需要特地更改。
信号发送的起点是K点,建立一个dist数组,dist[i]表示点K到点i的最短距离,显然dist[K]=0。假设一开始所有的点到K的距离都是Integer.MAX_VALUE,即无穷大。循环搜索离K最近的且没有到达过的一个点node,再更新点K到node的最小距离并将结果保存到dist[node]中。如果找不到新的点node,就表示信号已经传播结束。先根据dist判断所有的点是否全部到达(也可以通过receive来判断,但是不够简洁),再找到dist数组中的最大值并返回。
public int networkDelayTime(int[][] times, int N, int K) {
int[][] connect = new int[N+1][N+1];
for (int i = 0; i <= N; i ++)
for (int j = 0; j <= N; j ++)
connect[i][j] = -1;
// 记录连接信息
for (int[] t : times)
connect[t[0]][t[1]] = t[2];
// 记录到达情况
boolean[] receive = new boolean[N+1];
// 点K到点i的最短时间
int[] dist = new int[N+1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[K] = 0;
while (true) {
int node = -1;
int nodeDist = Integer.MAX_VALUE;
// 搜索最近的且没有到达的点
for (int i = 1; i <= N; i++) {
if (!receive[i] && dist[i] < nodeDist) {
nodeDist = dist[i];
node = i;
}
}
if (node == -1) break;
// 更新node的到达状态
receive[node] = true;
// 更新点K到node的最短时间
for (int i = 1; i <= N; i++) {
if (connect[node][i] != -1) {
dist[i] = Math.min(dist[i], dist[node] + connect[node][i]);
}
}
}
int res = 0;
for (int i = 1; i <= N; i++) {
if (dist[i] == Integer.MAX_VALUE) return -1;
res = Math.max(res, dist[i]);
}
return res;
}