|
| 1 | +package com.thealgorithms.datastructures.graphs; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Set; |
| 5 | +import java.util.TreeSet; |
| 6 | +import org.apache.commons.lang3.tuple.Pair; |
| 7 | + |
| 8 | +/** |
| 9 | + * Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph. |
| 10 | + */ |
| 11 | +public class DijkstraOptimizedAlgorithm { |
| 12 | + |
| 13 | + private final int vertexCount; |
| 14 | + |
| 15 | + /** |
| 16 | + * Constructs a Dijkstra object with the given number of vertices. |
| 17 | + * |
| 18 | + * @param vertexCount The number of vertices in the graph. |
| 19 | + */ |
| 20 | + public DijkstraOptimizedAlgorithm(int vertexCount) { |
| 21 | + this.vertexCount = vertexCount; |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices. |
| 26 | + * |
| 27 | + * The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i} |
| 28 | + * to vertex {@code j}. A value of 0 indicates no edge exists between the vertices. |
| 29 | + * |
| 30 | + * @param graph The graph represented as an adjacency matrix. |
| 31 | + * @param source The source vertex. |
| 32 | + * @return An array where the value at each index {@code i} represents the shortest distance from the source vertex to vertex {@code i}. |
| 33 | + * @throws IllegalArgumentException if the source vertex is out of range. |
| 34 | + */ |
| 35 | + public int[] run(int[][] graph, int source) { |
| 36 | + if (source < 0 || source >= vertexCount) { |
| 37 | + throw new IllegalArgumentException("Incorrect source"); |
| 38 | + } |
| 39 | + |
| 40 | + int[] distances = new int[vertexCount]; |
| 41 | + boolean[] processed = new boolean[vertexCount]; |
| 42 | + Set<Pair<Integer, Integer>> unprocessed = new TreeSet<>(); |
| 43 | + |
| 44 | + Arrays.fill(distances, Integer.MAX_VALUE); |
| 45 | + Arrays.fill(processed, false); |
| 46 | + distances[source] = 0; |
| 47 | + unprocessed.add(Pair.of(0, source)); |
| 48 | + |
| 49 | + while (!unprocessed.isEmpty()) { |
| 50 | + Pair<Integer, Integer> distanceAndU = unprocessed.iterator().next(); |
| 51 | + unprocessed.remove(distanceAndU); |
| 52 | + int u = distanceAndU.getRight(); |
| 53 | + processed[u] = true; |
| 54 | + |
| 55 | + for (int v = 0; v < vertexCount; v++) { |
| 56 | + if (!processed[v] && graph[u][v] != 0 && distances[u] != Integer.MAX_VALUE && distances[u] + graph[u][v] < distances[v]) { |
| 57 | + unprocessed.remove(Pair.of(distances[v], v)); |
| 58 | + distances[v] = distances[u] + graph[u][v]; |
| 59 | + unprocessed.add(Pair.of(distances[v], v)); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return distances; |
| 65 | + } |
| 66 | +} |
0 commit comments