1
+ import java .util .ArrayList ;
2
+ import java .util .Arrays ;
3
+ import java .util .HashMap ;
4
+ import java .util .List ;
5
+ import java .util .PriorityQueue ;
6
+
7
+ /**
8
+ * Finds the shortest paths from a source node to all other nodes in a graph using Dijkstra's algorithm.
9
+ *
10
+ * @param adjList The adjacency list representation of the graph where each edge has a weight.
11
+ * @param n The number of nodes in the graph.
12
+ * @param source The starting node for finding the shortest path.
13
+ * @return An array where the value at each index represents the shortest distance from the source to that node.
14
+ */
15
+ public class DijkstraAlgorithm {
16
+
17
+ static class Pair {
18
+ int node ;
19
+ int weight ;
20
+
21
+ Pair (int node , int weight ) {
22
+ this .node = node ;
23
+ this .weight = weight ;
24
+ }
25
+ }
26
+
27
+ public int [] dijkstra (HashMap <Integer , List <Pair >> adjList , int n , int source ) {
28
+ int [] distances = new int [n ];
29
+ Arrays .fill (distances , Integer .MAX_VALUE );
30
+ distances [source ] = 0 ;
31
+
32
+ PriorityQueue <Pair > pq = new PriorityQueue <>((a , b ) -> a .weight - b .weight );
33
+ pq .add (new Pair (source , 0 ));
34
+
35
+ while (!pq .isEmpty ()) {
36
+ Pair current = pq .poll ();
37
+ int currentNode = current .node ;
38
+ int currentWeight = current .weight ;
39
+
40
+ List <Pair > neighbors = adjList .get (currentNode );
41
+ if (neighbors != null ) {
42
+ for (Pair neighbor : neighbors ) {
43
+ int newDist = currentWeight + neighbor .weight ;
44
+ if (newDist < distances [neighbor .node ]) {
45
+ distances [neighbor .node ] = newDist ;
46
+ pq .add (new Pair (neighbor .node , newDist ));
47
+ }
48
+ }
49
+ }
50
+ }
51
+ return distances ;
52
+ }
53
+
54
+ public static void main (String [] args ) {
55
+ HashMap <Integer , List <Pair >> adjList = new HashMap <>();
56
+ adjList .put (0 , Arrays .asList (new Pair (1 , 4 ), new Pair (2 , 1 )));
57
+ adjList .put (1 , Arrays .asList (new Pair (3 , 1 )));
58
+ adjList .put (2 , Arrays .asList (new Pair (1 , 2 ), new Pair (3 , 5 )));
59
+ adjList .put (3 , new ArrayList <>());
60
+
61
+ DijkstraAlgorithm dijkstra = new DijkstraAlgorithm ();
62
+ int [] distances = dijkstra .dijkstra (adjList , 4 , 0 );
63
+
64
+ System .out .println ("Shortest distances from source 0:" );
65
+ for (int i = 0 ; i < distances .length ; i ++) {
66
+ System .out .println ("To node " + i + ": " + distances [i ]);
67
+ }
68
+ }
69
+ }
0 commit comments