1. // User function Template for Java
  2. class Pair
  3. {
  4. int vertex;
  5. int weight;
  6. Pair(int vertex, int weight)
  7. {
  8. this.vertex = vertex;
  9. this.weight = weight;
  10. }
  11. }
  12.  
  13. class Solution {
  14. /**
  15.   * 1. Create a adjancency list, for each node store {vertex, weight} as neighbour.
  16.   * 2. Find the topological sort of given graph and store it in stack
  17.   * 3. Create a distance array, assign all values as Int_MAX except source node will have distance as 0.
  18.   * 4. Run a loop until stack becomes empty
  19.   * - Relax the edges
  20.   * - For every neighbour check if distance[neighbour] > distance[currentNode] + weight
  21.   * - if yes, then update the distance of neighbour
  22.   * 5. if any vertex is unreachable then update distance as -1
  23.   * 6. Return the distance array
  24.   * */
  25. public int[] shortestPath(int V, int E, int[][] edges) {
  26. // Step-1 create a adjancency list
  27. // We will store neighbour nodes as well as weight between the nodes
  28. ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
  29. for(int i=0; i<V; i++)
  30. {
  31. adj.add(new ArrayList<Pair>());
  32. }
  33.  
  34. for(int[] edge : edges)
  35. {
  36. int u = edge[0];
  37. int v = edge[1];
  38. int w = edge[2];
  39. adj.get(u).add(new Pair(v, w));
  40. }
  41.  
  42. // Step-2 Find the topological sort
  43. Stack<Integer> st = new Stack<>();
  44. boolean[] visited = new boolean[V];
  45. for(int i=0; i<V; i++)
  46. {
  47. if(visited[i] == false)
  48. {
  49. topoSort(adj, visited, st, i);
  50. }
  51. }
  52.  
  53. // Step-3 define the distance array
  54. int[] distance = new int[V];
  55. Arrays.fill(distance, Integer.MAX_VALUE);
  56. distance[0] = 0;
  57.  
  58. // Step-4 relax the edges
  59. while(!st.isEmpty())
  60. {
  61. int node = st.pop();
  62.  
  63. for(Pair pair : adj.get(node))
  64. {
  65. int vertex = pair.vertex;
  66. int weight = pair.weight;
  67.  
  68. // relax the edges
  69. if(distance[node] != Integer.MAX_VALUE && (distance[vertex] > distance[node] + weight))
  70. {
  71. distance[vertex] = distance[node] + weight;
  72. }
  73. }
  74. }
  75.  
  76. // Step-5 if vertex is unreachable then update distance as -1
  77. for(int i=0;i<V;i++)
  78. {
  79. if(distance[i] == Integer.MAX_VALUE)
  80. distance[i] = -1;
  81. }
  82. return distance;
  83. }
  84.  
  85.  
  86. public void topoSort(ArrayList<ArrayList<Pair>> adj, boolean[] visited, Stack<Integer> st, int node)
  87. {
  88. visited[node] = true;
  89.  
  90. // traversing neighbouring nodes
  91. for(Pair p : adj.get(node))
  92. {
  93. int u = p.vertex;
  94. if(visited[u] == false)
  95. topoSort(adj,visited,st,u);
  96. }
  97. st.push(node);
  98. }
  99. }