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

Method dijkstra

DijkstraAlgorithm.java:10–39  ·  view source on GitHub ↗
(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S)

Source from the content-addressed store, hash-verified

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}

Callers

nothing calls this directly

Calls 1

isEmptyMethod · 0.45

Tested by

no test coverage detected