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 1:
1
2
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Dijkstra’s algorithm is ideal for finding the shortest time to reach all nodes in a weighted directed graph. By always expanding the node with the smallest current time, we ensure the earliest possible signal arrival at each node.
#include<vector>#include<queue>#include<unordered_map>usingnamespace std;
classSolution {
public:int networkDelayTime(vector<vector<int>>& times, int n, int k) {
vector<vector<pair<int,int>>> g(n+1);
for (auto& t : times) g[t[0]].emplace_back(t[1], t[2]);
vector<bool> vis(n+1, false);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
pq.emplace(0, k);
int ans =0, cnt =0;
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (vis[u]) continue;
vis[u] = true; ans = d; cnt++;
for (auto& [v, w] : g[u]) if (!vis[v]) pq.emplace(d+w, v);
}
return cnt == n ? ans : -1;
}
};
import java.util.*;
classSolution {
publicintnetworkDelayTime(int[][] times, int n, int k) {
Map<Integer, Map<Integer, Integer>> graph =new HashMap<>();
for (int i = 1; i <= n; i++) graph.put(i, new HashMap<>());
for (int[] t : times) graph.get(t[0]).put(t[1], t[2]);
Queue<int[]> pq =new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.add(newint[]{0, k});
boolean[] vis =newboolean[n+1];
int ans = 0, cnt = 0;
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int d = cur[0], u = cur[1];
if (vis[u]) continue;
vis[u]=true; ans = d; cnt++;
for (var entry : graph.get(u).entrySet()) {
int v = entry.getKey(), w = entry.getValue();
if (!vis[v]) pq.add(newint[]{d+w, v});
}
}
return cnt == n ? ans : -1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*
classSolution {
funnetworkDelayTime(times: Array<IntArray>, n: Int, k: Int): Int {
val graph = Array(n+1) { mutableListOf<Pair<Int,Int>>() }
for (t in times) graph[t[0]].add(t[1] to t[2])
val vis = BooleanArray(n+1)
val pq = PriorityQueue(compareBy<Pair<Int,Int>> { it.first })
pq.add(0 to k)
var ans = 0; var cnt = 0while (pq.isNotEmpty()) {
val(d, u) = pq.poll()
if (vis[u]) continue vis[u] = true; ans = d; cnt++for ((v, w) in graph[u]) if (!vis[v]) pq.add(d+w to v)
}
returnif (cnt == n) ans else -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import heapq
classSolution:
defnetworkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:
from collections import defaultdict
g = defaultdict(list)
for u, v, w in times:
g[u].append((v, w))
vis = set()
pq = [(0, k)]
ans =0while pq:
d, u = heapq.heappop(pq)
if u in vis: continue vis.add(u); ans = d
for v, w in g[u]:
if v notin vis:
heapq.heappush(pq, (d+w, v))
return ans if len(vis) == n else-1