MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

NetworkDelayTime.java:1–48  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2 public int[] dijkstra(int src,int n, ArrayList<ArrayList<int[]>> adj){
3 // pair -> (node, time)
4 PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
5 public int compare(int p1[], int p2[]){
6 return p1[1] - p2[1];
7 }
8 });
9 int time[] = new int[n];
10 Arrays.fill(time,Integer.MAX_VALUE);
11 time[src] = 0;
12 pq.offer(new int[]{src,0});
13 while(!pq.isEmpty()){
14 int pair[] = pq.poll();
15 int u = pair[0];
16 int d = pair[1];
17 if(d > time[u]) continue;
18 for(int neighbour[] : adj.get(u)){
19 int v = neighbour[0];
20 int w = neighbour[1];
21 if(time[u] + w < time[v]){
22 time[v] = time[u] + w;
23 pq.offer(new int[]{v, time[v]});
24 }
25 }
26 }
27 return time;
28 }
29 //time complexity!
30 public int networkDelayTime(int[][] times, int n, int k) {
31 ArrayList<ArrayList<int[]>> adj = new ArrayList<>();
32 for(int i=0;i<n;i++){
33 adj.add(new ArrayList<>());
34 }
35 for(int time[] : times){
36 int u = time[0]-1;
37 int v = time[1]-1;
38 int w = time[2];
39 adj.get(u).add(new int[]{v,w});
40 }
41 int minTime[] = dijkstra(k-1,n, adj);
42 int res = Integer.MIN_VALUE;
43 for(int time : minTime){
44 res = Math.max(res,time);
45 }
46 return (res==Integer.MAX_VALUE)?-1:res;
47 }
48}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected