Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.thealgorithms.datastructures.graphs;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
* Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph.
Expand All @@ -18,6 +19,21 @@ public DijkstraAlgorithm(int vertexCount) {
this.vertexCount = vertexCount;
}

private static class Node implements Comparable<Node> {
int id;
int distance;

Node(int id, int distance) {
this.id = id;
this.distance = distance;
}

@Override
public int compareTo(Node other) {
return Integer.compare(this.distance, other.distance);
}
}

/**
* Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices.
*
Expand All @@ -36,18 +52,25 @@ public int[] run(int[][] graph, int source) {

int[] distances = new int[vertexCount];
boolean[] processed = new boolean[vertexCount];
PriorityQueue<Node> unprocessed = new PriorityQueue<>();

Arrays.fill(distances, Integer.MAX_VALUE);
Arrays.fill(processed, false);
distances[source] = 0;
unprocessed.add(new Node(source, 0));

while (!unprocessed.isEmpty()) {
Node current = unprocessed.poll();
int u = current.id;

for (int count = 0; count < vertexCount - 1; count++) {
int u = getMinDistanceVertex(distances, processed);
if (processed[u]) {
continue;
}
processed[u] = true;

for (int v = 0; v < vertexCount; v++) {
if (!processed[v] && graph[u][v] != 0 && distances[u] != Integer.MAX_VALUE && distances[u] + graph[u][v] < distances[v]) {
distances[v] = distances[u] + graph[u][v];
unprocessed.add(new Node(v, distances[v]));
}
}
}
Expand All @@ -56,27 +79,6 @@ public int[] run(int[][] graph, int source) {
return distances;
}

/**
* Finds the vertex with the minimum distance value from the set of vertices that have not yet been processed.
*
* @param distances The array of current shortest distances from the source vertex.
* @param processed The array indicating whether each vertex has been processed.
* @return The index of the vertex with the minimum distance value.
*/
private int getMinDistanceVertex(int[] distances, boolean[] processed) {
int min = Integer.MAX_VALUE;
int minIndex = -1;

for (int v = 0; v < vertexCount; v++) {
if (!processed[v] && distances[v] <= min) {
min = distances[v];
minIndex = v;
}
}

return minIndex;
}

/**
* Prints the shortest distances from the source vertex to all other vertices.
*
Expand Down

This file was deleted.

This file was deleted.

Loading