Single source shortest path algo
Wed Nov 06 2024 16:39:37 GMT+0000 (Coordinated Universal Time)
Saved by @signin
import java.util.*;
class Graph {
private final int vertices;
private final List<List<Node>> adjList;
static class Node implements Comparable<Node> {
int vertex, weight;
Node(int vertex, int weight) {
this.vertex = vertex;
this.weight = weight;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.weight, other.weight);
}
}
public Graph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
adjList.add(new ArrayList<>());
}
}
public void addEdge(int src, int dest, int weight) {
adjList.get(src).add(new Node(dest, weight));
adjList.get(dest).add(new Node(src, weight)); // For undirected graph; remove if directed
}
public void dijkstra(int source) {
int[] dist = new int[vertices];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
priorityQueue.add(new Node(source, 0));
while (!priorityQueue.isEmpty()) {
Node current = priorityQueue.poll();
int u = current.vertex;
for (Node neighbor : adjList.get(u)) {
int v = neighbor.vertex;
int weight = neighbor.weight;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
priorityQueue.add(new Node(v, dist[v]));
}
}
}
printSolution(dist, source);
}
private void printSolution(int[] dist, int source) {
System.out.println("Vertex\t\tDistance from Source " + source);
for (int i = 0; i < vertices; i++) {
System.out.println(i + "\t\t" + dist[i]);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input number of vertices and edges
System.out.print("Enter the number of vertices: ");
int vertices = scanner.nextInt();
System.out.print("Enter the number of edges: ");
int edges = scanner.nextInt();
Graph graph = new Graph(vertices);
// Input edges
System.out.println("Enter each edge (source, destination, weight):");
for (int i = 0; i < edges; i++) {
int src = scanner.nextInt();
int dest = scanner.nextInt();
int weight = scanner.nextInt();
graph.addEdge(src, dest, weight);
}
// Input the source vertex
System.out.print("Enter the source vertex: ");
int source = scanner.nextInt();
// Run Dijkstra's algorithm
graph.dijkstra(source);
scanner.close();
}
}



Comments