1. class Pair
  2. {
  3. int vertex;
  4. int weight;
  5. Pair(int vertex, int weight)
  6. {
  7. this.vertex = vertex;
  8. this.weight = weight;
  9. }
  10. }
  11.  
  12. class Solution {
  13. /**
  14.   If you see: "shortest time / delay / distance", weights present, no DAG guarantee
  15.   then Instantly think: Dijkstra
  16.   Idea: give me the node with the smallest distance first using dijkastra algorithm
  17.   */
  18. public int networkDelayTime(int[][] times, int n, int k) {
  19.  
  20. // Step-1 Create an adjacency list where each node has {vertex, weight}
  21. ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
  22. for(int i=0; i<=n; i++)
  23. {
  24. adj.add(new ArrayList<Pair>());
  25. }
  26.  
  27. for(int[] edge : times)
  28. {
  29. int u = edge[0];
  30. int v = edge[1];
  31. int w = edge[2];
  32.  
  33. adj.get(u).add(new Pair(v,w));
  34. }
  35.  
  36. // Step-2 Create a distance array
  37. int[] distance = new int[n+1];
  38. Arrays.fill(distance, Integer.MAX_VALUE);
  39. distance[k] = 0;
  40.  
  41. // Step-3 Store the nodes into MIN-HEAP accoriding to node's weight to distances
  42. PriorityQueue<Pair> pq = new PriorityQueue<>(
  43. (a,b) -> Integer.compare(a.weight, b.weight)
  44. );
  45. pq.offer(new Pair(k, 0));
  46.  
  47. // Step-4 Relax the edges
  48. while(!pq.isEmpty())
  49. {
  50. Pair pair = pq.poll();
  51. int currentNode = pair.vertex;
  52.  
  53. for(Pair neighbour : adj.get(currentNode))
  54. {
  55. int vertex = neighbour.vertex;
  56. int weight = neighbour.weight;
  57.  
  58. if(distance[vertex] > distance[currentNode] + weight)
  59. {
  60. distance[vertex] = distance[currentNode] + weight;
  61. pq.offer(new Pair(vertex, distance[vertex]));
  62. }
  63. }
  64. }
  65.  
  66. // Step-5 If any node is unreachable then return -1
  67. // the distance array contains the shortest path from k to every node.
  68. int maxDistance = 0;
  69. for(int i=1; i<=n; i++)
  70. {
  71. if(distance[i] == Integer.MAX_VALUE)
  72. return -1;
  73. // maximum of all shortest distances, because that’s when the signal has reached everyone.
  74. maxDistance = Math.max(maxDistance, distance[i]);
  75. }
  76. return maxDistance;
  77. }
  78. }