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
2 changes: 2 additions & 0 deletions desktop.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[.ShellClassInfo]
LocalizedResourceName=@dijkstra-priority-queue,0
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ public void merge(ORSet<T> other) {
*/
public static class Pair<T> {
private final T element;
private final String uniqueTag;

/**
* Constructs a pair with the specified element and unique tag.
Expand All @@ -176,7 +175,6 @@ public static class Pair<T> {
*/
public Pair(T element, String uniqueTag) {
this.element = element;
this.uniqueTag = uniqueTag;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
*
* @param <E> the type of elements held in this list
*/
@SuppressWarnings("rawtypes")
public class CircleLinkedList<E> {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,6 @@ private static class Node<E> {
private final List<Node<E>> forward;
private final List<Node<E>> backward;

@SuppressWarnings("unchecked")
Node(E value, int height) {
this.value = value;
this.height = height;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public class StackArray<T> implements Stack<T> {
/**
* Creates a stack with a default capacity.
*/
@SuppressWarnings("unchecked")
public StackArray() {
this(DEFAULT_CAPACITY);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.thealgorithms.graphs;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

/**
* Dijkstra's algorithm finds the shortest path from a source vertex to all other vertices
* in a weighted graph. This implementation uses a PriorityQueue for optimal performance.
*
* Applications: GPS routing (Google Maps), Network routing (OSPF protocol).
*
* Time Complexity: O((V + E) log V)
* Space Complexity: O(V)
*/
public class DijkstraPriorityQueue {

public static class Edge {
int target;
int weight;

public Edge(int target, int weight) {
this.target = target;
this.weight = weight;
}
}

/**
* Finds the shortest paths from the source to all other vertices.
*
* @param source the starting vertex
* @param graph the adjacency list representation of the graph
* @param numVertices total number of vertices in the graph
* @return an array of shortest distances from source
* @throws IllegalArgumentException if any edge weight is negative or input is invalid
*/
public int[] runDijkstra(int source, Map<Integer, List<Edge>> graph, int numVertices) {
// Validation for number of vertices
if (numVertices <= 0) {
return new int[0];
}

// Validation for null graph or invalid source index
if (graph == null || source < 0 || source >= numVertices) {
int[] emptyDist = new int[numVertices];
Arrays.fill(emptyDist, Integer.MAX_VALUE);
if (source >= 0 && source < numVertices) {
emptyDist[source] = 0;
}
return emptyDist;
}

// Min-priority queue based on distance (int[1])
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
int[] dist = new int[numVertices];
Arrays.fill(dist, Integer.MAX_VALUE);

dist[source] = 0;
pq.add(new int[] {source, 0});

while (!pq.isEmpty()) {
int[] current = pq.poll();
int u = current[0];
int d = current[1];

// If current distance is already greater than stored distance, skip
// This is a common "Partial" coverage point if not tested with multiple paths
if (d > dist[u]) {
continue;
}

List<Edge> neighbors = graph.get(u);
if (neighbors == null) {
continue;
}

for (Edge edge : neighbors) {
// Dijkstra's algorithm does not support negative weights
if (edge.weight < 0) {
throw new IllegalArgumentException("Graph contains negative weight edge: " + edge.weight);
}

if (dist[u] != Integer.MAX_VALUE && dist[u] + edge.weight < dist[edge.target]) {
dist[edge.target] = dist[u] + edge.weight;
pq.add(new int[] {edge.target, dist[edge.target]});
}
}
}
return dist;
}
}
72 changes: 51 additions & 21 deletions src/main/java/com/thealgorithms/others/Dijkstra.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.thealgorithms.others;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.PriorityQueue;

/**
* Dijkstra's algorithm,is a graph search algorithm that solves the
* single-source shortest path problem for a graph with nonnegative edge path
Expand All @@ -12,7 +13,10 @@
* <p>
* NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph
* consisting of 2 or more nodes, generally represented by an adjacency matrix
* or list, and a start node.
* or list, and a start node. This implementation uses a binary heap
* (Java's {@link PriorityQueue}) to achieve a time complexity of
* O((V + E) log V) in practice. Practical use-cases include GPS routing and
* network routing where all edge weights are non-negative.
*
* <p>
* Original source of code:
Expand Down Expand Up @@ -182,46 +186,72 @@ public void dijkstra(String startName) {
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();

// set-up vertices
// initialize distances
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 : Integer.MAX_VALUE;
q.add(v);
}

dijkstra(q);
}
// Priority queue of (vertex, knownDist) entries. We push new entries when
// a shorter distance is found; stale entries are ignored when polled.
PriorityQueue<NodeEntry> pq = new PriorityQueue<>(Comparator
.comparingInt((NodeEntry e) -> e.dist)
.thenComparing(e -> e.vertex.name));

pq.add(new NodeEntry(source, 0));

dijkstra(pq);
}
/**
* Implementation of dijkstra's algorithm using a binary heap.
* Implementation of dijkstra's algorithm using a priority queue of entries.
*/
private void dijkstra(final NavigableSet<Vertex> q) {
Vertex u;
Vertex v;
while (!q.isEmpty()) {
// vertex with shortest distance (first iteration will return source)
u = q.pollFirst();
private void dijkstra(final PriorityQueue<NodeEntry> pq) {
while (!pq.isEmpty()) {
final NodeEntry entry = pq.poll();
final Vertex u = entry.vertex;

// ignore stale/popped entries
if (entry.dist != u.dist) {
continue;
}

if (u.dist == Integer.MAX_VALUE) {
break; // we can ignore u (and any other remaining vertices) since they are
// unreachable
break; // remaining vertices are unreachable
}

// look at distances to each neighbour
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
v = a.getKey(); // the neighbour in this iteration
final Vertex v = a.getKey(); // the neighbour in this iteration
final int weight = a.getValue();

final int alternateDist = u.dist + a.getValue();
if (weight < 0) {
throw new IllegalArgumentException("Graph contains negative edge weight: " + weight);
}

final int alternateDist = u.dist + weight;
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
pq.add(new NodeEntry(v, alternateDist));
}
}
}
}

/**
* Helper entry for the priority queue to avoid costly removals (no decrease-key).
*/
private static class NodeEntry {
final Vertex vertex;
final int dist;

NodeEntry(Vertex vertex, int dist) {
this.vertex = vertex;
this.dist = dist;
}
}

/**
* Prints a path from the source to the specified vertex
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ public final class DampedOscillator {
/** Damping coefficient (s⁻¹). */
private final double gamma;

private DampedOscillator() {
throw new AssertionError("No instances.");
}

/**
* Constructs a damped oscillator model.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
*/
public final class SimplePendulumRK4 {

private SimplePendulumRK4() {
throw new AssertionError("No instances.");
}

private final double length; // meters
private final double g; // acceleration due to gravity (m/s^2)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
* This scheduling algorithm is ideal for real-time systems where meeting deadlines is critical.
*/
public final class EDFScheduling {
private EDFScheduling() {
}

private List<Process> processes;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,12 @@ private HighestResponseRatioNextScheduling() {
* Represents a process in the scheduling algorithm.
*/
private static class Process {
String name;
int arrivalTime;
int burstTime;
int turnAroundTime;
boolean finished;

Process(String name, int arrivalTime, int burstTime) {
this.name = name;
this.arrivalTime = arrivalTime;
this.burstTime = burstTime;
this.turnAroundTime = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
* Processes with more tickets have a higher chance of being selected.
*/
public final class LotteryScheduling {
private LotteryScheduling() {
}

private List<Process> processes;
private Random random;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ public class PerfectBinarySearch<T> implements SearchAlgorithm {
/**
* @param array is an array where the element should be found
* @param key is an element which should be found
* @param <T> is any comparable type
* @param <U> is any comparable type
* @return index of the element
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
public <U extends Comparable<U>> int find(U[] array, U key) {
return search(array, key, 0, array.length - 1);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.thealgorithms.sorts;

public class AdaptiveMergeSort implements SortAlgorithm {
@SuppressWarnings("unchecked")
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length <= 1) {
return array;
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/thealgorithms/sorts/SpreadSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ int size() {
*
* @return an array containing all elements in the bucket
*/
@SuppressWarnings("unchecked")
T[] toArray() {
return Arrays.copyOf(elements, size);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ void testIterator() {
void testIteratorEmptyBag() {
Bag<String> bag = new Bag<>();
int count = 0;
for (String ignored : bag) {
for (String item : bag) {
org.junit.jupiter.api.Assertions.fail("Iterator should not return any items for an empty bag");
}
assertEquals(0, count, "Iterator should not traverse any items in an empty bag");
Expand Down
Loading
Loading