| 8 | //Function to find the shortest distance of all the vertices |
| 9 | //from the source vertex S. |
| 10 | static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S) |
| 11 | { |
| 12 | // Write your code here |
| 13 | // [node, dist] |
| 14 | PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){ |
| 15 | public int compare(int p1[], int p2[]){ |
| 16 | return p1[1] - p2[1]; |
| 17 | } |
| 18 | }); |
| 19 | int dist[] = new int[V]; |
| 20 | Arrays.fill(dist,Integer.MAX_VALUE); |
| 21 | dist[S] = 0; |
| 22 | pq.offer(new int[]{S,0}); |
| 23 | while(!pq.isEmpty()){ |
| 24 | int pair[] = pq.poll(); |
| 25 | int u = pair[0]; |
| 26 | int d = pair[1]; |
| 27 | if(d > dist[u]) continue; |
| 28 | for(ArrayList<Integer> neighbour : adj.get(u)){ |
| 29 | int v = neighbour.get(0); |
| 30 | int w = neighbour.get(1); |
| 31 | if(dist[u] + w < dist[v]){ |
| 32 | dist[v] = dist[u] + w; |
| 33 | pq.offer(new int[]{v,dist[v]}); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | } |
| 38 | return dist; |
| 39 | } |
| 40 | } |