Medium
There is an undirected graph of n
nodes. You are given a 2D array edges
, where edges[i] = [ui, vi, lengthi]
describes an edge between node ui
and node vi
with a traversal time of lengthi
units.
Additionally, you are given an array disappear
, where disappear[i]
denotes the time when the node i
disappears from the graph and you won’t be able to visit it.
Notice that the graph might be disconnected and might contain multiple edges.
Return the array answer
, with answer[i]
denoting the minimum units of time required to reach node i
from node 0. If node i
is unreachable from node 0 then answer[i]
is -1
.
Example 1:
Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]
Output: [0,-1,4]
Explanation:
We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
edges[0]
. Unfortunately, it disappears at that moment, so we won’t be able to visit it.edges[2]
.Example 2:
Input: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]
Output: [0,2,3]
Explanation:
We are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
edges[0]
.edges[0]
and edges[1]
.Example 3:
Input: n = 2, edges = [[0,1,1]], disappear = [1,1]
Output: [0,-1]
Explanation:
Exactly when we reach node 1, it disappears.
Constraints:
1 <= n <= 5 * 104
0 <= edges.length <= 105
edges[i] == [ui, vi, lengthi]
0 <= ui, vi <= n - 1
1 <= lengthi <= 105
disappear.length == n
1 <= disappear[i] <= 105
import java.util.Arrays;
public class Solution {
public int[] minimumTime(int n, int[][] edges, int[] disappear) {
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
boolean exit = false;
int i;
int src;
int dest;
int cost;
dist[0] = 0;
for (i = 0; i < n && !exit; ++i) {
exit = true;
for (int[] edge : edges) {
src = edge[0];
dest = edge[1];
cost = edge[2];
if (dist[src] != -1
&& dist[src] != Integer.MAX_VALUE
&& dist[src] < disappear[src]
&& dist[src] + cost < dist[dest]) {
exit = false;
dist[dest] = dist[src] + cost;
}
if (dist[dest] != -1
&& dist[dest] != Integer.MAX_VALUE
&& dist[dest] < disappear[dest]
&& dist[dest] + cost < dist[src]) {
exit = false;
dist[src] = dist[dest] + cost;
}
}
}
for (i = 0; i < dist.length; ++i) {
if (dist[i] == Integer.MAX_VALUE || dist[i] >= disappear[i]) {
dist[i] = -1;
}
}
return dist;
}
}