Leetcode 743. Network Delay Time
You are given a network of n
nodes, labeled from 1
to n
. You are also given times
, a list of travel times as directed edges times[i] = (ui, vi, wi)
, where ui
is the source node, vi
is the target node, and wi
is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k
. Return the time it takes for all the n
nodes to receive the signal. If it is impossible for all the n
nodes to receive the signal, return -1
.
Example:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
k
.(target, weight)
pairs.k
to all other nodes.
-1
.import java.util.*;
public class NetworkDelayTime {
public int networkDelayTime(int[][] times, int n, int k) {
// Initialize the graph as an adjacency list
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int i = 1; i <= n; i++) {
graph.put(i, new ArrayList<>());
}
for (int[] time : times) {
graph.get(time[0]).add(new int[]{time[1], time[2]});
}
// Dijkstra's Algorithm
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[k] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.offer(new int[]{k, 0});
while (!pq.isEmpty()) {
int[] current = pq.poll();
int node = current[0];
int time = current[1];
if (time > dist[node]) continue;
for (int[] neighbor : graph.get(node)) {
int nextNode = neighbor[0];
int travelTime = neighbor[1];
int newDist = dist[node] + travelTime;
if (newDist < dist[nextNode]) {
dist[nextNode] = newDist;
pq.offer(new int[]{nextNode, newDist});
}
}
}
int maxTime = Arrays.stream(dist).skip(1).max().getAsInt();
return maxTime == Integer.MAX_VALUE ? -1 : maxTime;
}
public static void main(String[] args) {
NetworkDelayTime solution = new NetworkDelayTime();
int[][] times = \ use example from above
int n = 4;
int k = 2;
System.out.println(solution.networkDelayTime(times, n, k)); // Output: 2
}
}
The overall time complexity is O((V + E) log V). This should perform efficiently given typical problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?