1+ package com .thealgorithms .graphs ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Arrays ;
5+ import java .util .Comparator ;
6+ import java .util .List ;
7+ import java .util .Map ;
8+ import java .util .PriorityQueue ;
9+
10+ /**
11+ * Dijkstra's algorithm finds the shortest path from a source vertex to all other vertices
12+ * in a weighted graph. This implementation uses a PriorityQueue for optimal performance.
13+ *
14+ * Applications: GPS routing (Google Maps), Network routing (OSPF protocol).
15+ *
16+ * Time Complexity: O((V + E) log V)
17+ * Space Complexity: O(V)
18+ */
19+ public class DijkstraPriorityQueue {
20+
21+ public static class Edge {
22+ int target ;
23+ int weight ;
24+
25+ public Edge (int target , int weight ) {
26+ this .target = target ;
27+ this .weight = weight ;
28+ }
29+ }
30+
31+ /**
32+ * Finds the shortest paths from the source to all other vertices.
33+ *
34+ * @param source the starting vertex
35+ * @param graph the adjacency list representation of the graph
36+ * @param numVertices total number of vertices in the graph
37+ * @return an array of shortest distances from source
38+ * @throws IllegalArgumentException if any edge weight is negative
39+ */
40+ public int [] runDijkstra (int source , Map <Integer , List <Edge >> graph , int numVertices ) {
41+ if (numVertices <= 0 ) {
42+ return new int [0 ];
43+ }
44+
45+ // Min-priority queue based on distance (int[1])
46+ PriorityQueue <int []> pq = new PriorityQueue <>(Comparator .comparingInt (a -> a [1 ]));
47+ int [] dist = new int [numVertices ];
48+ Arrays .fill (dist , Integer .MAX_VALUE );
49+
50+ dist [source ] = 0 ;
51+ pq .add (new int [] {source , 0 });
52+
53+ while (!pq .isEmpty ()) {
54+ int [] current = pq .poll ();
55+ int u = current [0 ];
56+ int d = current [1 ];
57+
58+ // If current distance is already greater than stored distance, skip
59+ if (d > dist [u ]) {
60+ continue ;
61+ }
62+
63+ for (Edge edge : graph .getOrDefault (u , new ArrayList <>())) {
64+ // Dijkstra's algorithm does not support negative weights
65+ if (edge .weight < 0 ) {
66+ throw new IllegalArgumentException ("Graph contains negative weight edge: " + edge .weight );
67+ }
68+
69+ if (dist [u ] + edge .weight < dist [edge .target ]) {
70+ dist [edge .target ] = dist [u ] + edge .weight ;
71+ pq .add (new int [] {edge .target , dist [edge .target ]});
72+ }
73+ }
74+ }
75+ return dist ;
76+ }
77+ }
0 commit comments