|
| 1 | +package com.thealgorithms.graphs; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Implementation of Dijkstra's Algorithm. |
| 7 | + * Finds the shortest path from a given source node to all other nodes in a weighted graph. |
| 8 | + * |
| 9 | + * @author: poorvikaa08 |
| 10 | + * @date: 19 October 2025 (Sunday) |
| 11 | + * @wiki: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm |
| 12 | + */ |
| 13 | +public class DijkstrasAlgorithm { |
| 14 | + |
| 15 | + /** |
| 16 | + * Computes the shortest distance from a source vertex to all other vertices. |
| 17 | + * |
| 18 | + * @param graph adjacency list representing the graph, where graph[u] contains pairs (v, weight) |
| 19 | + * @param src the source vertex |
| 20 | + * @param V total number of vertices |
| 21 | + * @return an array of shortest distances from src to every vertex |
| 22 | + */ |
| 23 | + public static int[] dijkstra(List<List<Node>> graph, int src, int V) { |
| 24 | + int[] dist = new int[V]; |
| 25 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 26 | + dist[src] = 0; |
| 27 | + |
| 28 | + PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(n -> n.weight)); |
| 29 | + pq.add(new Node(src, 0)); |
| 30 | + |
| 31 | + while (!pq.isEmpty()) { |
| 32 | + Node curr = pq.poll(); |
| 33 | + for (Node neighbor : graph.get(curr.vertex)) { |
| 34 | + int newDist = dist[curr.vertex] + neighbor.weight; |
| 35 | + if (newDist < dist[neighbor.vertex]) { |
| 36 | + dist[neighbor.vertex] = newDist; |
| 37 | + pq.add(new Node(neighbor.vertex, newDist)); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + return dist; |
| 43 | + } |
| 44 | + |
| 45 | + /** Helper class representing an edge or connection to another vertex */ |
| 46 | + public static class Node { |
| 47 | + int vertex; |
| 48 | + int weight; |
| 49 | + |
| 50 | + public Node(int vertex, int weight) { |
| 51 | + this.vertex = vertex; |
| 52 | + this.weight = weight; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments