Skip to content

Graph algorithm #6060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
47 changes: 47 additions & 0 deletions src/main/java/com/thealgorithms/graph/DijkstraShortestPath.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import java.util.*;

public class DijkstraShortestPath {

/**
* Finds the shortest path distances from the startNode to all other nodes in a weighted graph.
*
* @param n The number of nodes in the graph.
* @param adjList The adjacency list where each entry contains pairs of neighboring nodes and edge weights.
* @param startNode The starting node for the shortest path calculation.
* @return An array where each index i contains the shortest distance from startNode to node i.
*/
public int[] shortestPath(int n, Map<Integer, List<int[]>> adjList, int startNode) {
int[] distances = new int[n];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[startNode] = 0;

PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
minHeap.offer(new int[]{startNode, 0});

while (!minHeap.isEmpty()) {
int[] current = minHeap.poll();
int currentNode = current[0];
int currentDistance = current[1];

if (currentDistance > distances[currentNode]) {
continue;
}

List<int[]> neighbors = adjList.getOrDefault(currentNode, new ArrayList<>());
for (int[] neighbor : neighbors) {
int nextNode = neighbor[0];
int edgeWeight = neighbor[1];

int newDistance = distances[currentNode] + edgeWeight;
if (newDistance < distances[nextNode]) {
distances[nextNode] = newDistance;
minHeap.offer(new int[]{nextNode, newDistance});
}
}
}

return distances;
}
}

//https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#:~:text=Dijkstra's%20algorithm%20(/%CB%88da%C9%AA,and%20published%20three%20years%20later.
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class DijkstraShortestPathTest {

private DijkstraShortestPath dijkstra;

@BeforeEach
public void setUp() {
dijkstra = new DijkstraShortestPath();
}

@Test
public void testSinglePath() {
// Simple graph where the path is straightforward
Map<Integer, List<int[]>> adjList = new HashMap<>();
adjList.put(0, List.of(new int[]{1, 1}));
adjList.put(1, List.of(new int[]{2, 1}));
adjList.put(2, List.of(new int[]{3, 1}));
adjList.put(3, new ArrayList<>());

int[] result = dijkstra.shortestPath(4, adjList, 0);

int[] expected = {0, 1, 2, 3};
assertArrayEquals(expected, result, "Shortest path distances should match.");
}

@Test
public void testDisconnectedGraph() {
// Graph where some nodes are unreachable
Map<Integer, List<int[]>> adjList = new HashMap<>();
adjList.put(0, List.of(new int[]{1, 2}));
adjList.put(1, List.of(new int[]{2, 2}));
adjList.put(2, new ArrayList<>());
adjList.put(3, new ArrayList<>());

int[] result = dijkstra.shortestPath(4, adjList, 0);

int[] expected = {0, 2, 4, Integer.MAX_VALUE}; // node 3 is disconnected
assertArrayEquals(expected, result, "Shortest path should indicate unreachable nodes.");
}

@Test
public void testComplexGraph() {
// Complex graph with multiple paths
Map<Integer, List<int[]>> adjList = new HashMap<>();
adjList.put(0, List.of(new int[]{1, 4}, new int[]{2, 1}));
adjList.put(1, List.of(new int[]{3, 1}));
adjList.put(2, List.of(new int[]{1, 2}, new int[]{3, 5}));
adjList.put(3, new ArrayList<>());

int[] result = dijkstra.shortestPath(4, adjList, 0);

int[] expected = {0, 3, 1, 4};
assertArrayEquals(expected, result, "Distances should match expected shortest path distances.");
}
}
Loading