-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraAlgorithm.java
More file actions
64 lines (51 loc) · 1.9 KB
/
DijkstraAlgorithm.java
File metadata and controls
64 lines (51 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.*;
public class DijkstraAlgorithm {
static class Edge {
int target;
int weight;
Edge(int target, int weight) {
this.target = target;
this.weight = weight;
}
}
static void dijkstra(List<List<Edge>> graph, int source) {
int V = graph.size();
int[] distance = new int[V];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[source] = 0;
// Priority queue to keep track of nodes with the minimum distance
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(o -> distance[o]));
pq.add(source);
while (!pq.isEmpty()) {
int u = pq.poll();
for (Edge edge : graph.get(u)) {
int v = edge.target;
int weight = edge.weight;
if (distance[u] + weight < distance[v]) {
distance[v] = distance[u] + weight;
pq.add(v);
}
}
}
// Print the shortest distances from the source node to all other nodes
for (int i = 0; i < V; i++) {
System.out.println("Shortest distance from node " + source + " to node " + i + ": " + distance[i]);
}
}
public static void main(String[] args) {
int V = 5; // Number of vertices
List<List<Edge>> graph = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
graph.add(new ArrayList<>());
}
// Adding edges to the graph (example graph with weighted edges)
graph.get(0).add(new Edge(1, 9));
graph.get(0).add(new Edge(2, 6));
graph.get(0).add(new Edge(3, 5));
graph.get(0).add(new Edge(4, 3));
graph.get(2).add(new Edge(1, 2));
graph.get(2).add(new Edge(3, 4));
int sourceNode = 0; // Source node for Dijkstra's algorithm
dijkstra(graph, sourceNode);
}
}