File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .graphs ;
2+
3+ import java .util .*;
4+
5+ public class Dijkstra {
6+
7+ public static int [] dijkstra (List <List <int []>> graph , int source ) {
8+ int n = graph .size ();
9+ int [] dist = new int [n ];
10+ Arrays .fill (dist , Integer .MAX_VALUE );
11+ dist [source ] = 0 ;
12+
13+ PriorityQueue <int []> pq =
14+ new PriorityQueue <>(Comparator .comparingInt (a -> a [1 ]));
15+
16+ pq .offer (new int []{source , 0 });
17+
18+ while (!pq .isEmpty ()) {
19+ int [] curr = pq .poll ();
20+ int u = curr [0 ];
21+ int d = curr [1 ];
22+
23+ if (d > dist [u ]) continue ;
24+
25+ for (int [] edge : graph .get (u )) {
26+ int v = edge [0 ];
27+ int w = edge [1 ];
28+
29+ if (w < 0 ) {
30+ throw new IllegalArgumentException ("Negative weight detected" );
31+ }
32+
33+ if (dist [u ] + w < dist [v ]) {
34+ dist [v ] = dist [u ] + w ;
35+ pq .offer (new int []{v , dist [v ]});
36+ }
37+ }
38+ }
39+ return dist ;
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments