Skip to content

Commit 39b0944

Browse files
author
Farai Mugaviri
committed
Added Dijkstra's Algorithm in Greedy Algorithms
1 parent 3c70a54 commit 39b0944

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Dijkstra's shortest path algorithm for non-negative weighted graphs.
7+
*
8+
* Provides a method to compute shortest distances from a source node to all
9+
* other nodes using an adjacency list representation.
10+
*/
11+
public final class Dijkstra {
12+
private Dijkstra() {}
13+
14+
/**
15+
* Compute shortest distances from source to all vertices.
16+
*
17+
* @param n number of vertices (vertices are 0..n-1)
18+
* @param adj adjacency list where adj[u] is a list of (v, weight) pairs
19+
* @param src source vertex
20+
* @return array of distances where dist[i] is shortest distance or Long.MAX_VALUE if unreachable
21+
*/
22+
public static long[] shortestPaths(int n, List<List<Edge>> adj, int src) {
23+
long[] dist = new long[n];
24+
Arrays.fill(dist, Long.MAX_VALUE);
25+
dist[src] = 0L;
26+
27+
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a.dist));
28+
pq.add(new Node(src, 0L));
29+
30+
boolean[] visited = new boolean[n];
31+
32+
while (!pq.isEmpty()) {
33+
Node cur = pq.poll();
34+
int u = cur.id;
35+
if (visited[u]) continue;
36+
visited[u] = true;
37+
38+
for (Edge e : adj.get(u)) {
39+
int v = e.to;
40+
long w = e.weight;
41+
if (dist[u] != Long.MAX_VALUE && dist[u] + w < dist[v]) {
42+
dist[v] = dist[u] + w;
43+
pq.add(new Node(v, dist[v]));
44+
}
45+
}
46+
}
47+
48+
return dist;
49+
}
50+
51+
/** Simple edge class for adjacency lists */
52+
public static class Edge {
53+
public final int to;
54+
public final long weight;
55+
56+
public Edge(int to, long weight) {
57+
this.to = to;
58+
this.weight = weight;
59+
}
60+
}
61+
62+
private static class Node {
63+
final int id;
64+
final long dist;
65+
66+
Node(int id, long dist) {
67+
this.id = id;
68+
this.dist = dist;
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)