Dijkstra's algorithm is a classic solution for finding the shortest path in a weighted graph with non-negative edge weights. Below is a complete JavaScript implementation of Dijkstra's algorithm.
✅ Example: Dijkstra's Algorithm in JavaScript
We’ll represent the graph using an adjacency list, and we’ll use a priority queue implemented with a min-heap (for simplicity, we’ll simulate it using arrays here).
class PriorityQueue {
constructor() {
this.nodes = [];
}
enqueue(priority, key) {
this.nodes.push({ key, priority });
this.sort();
}
dequeue() {
return this.nodes.shift();
}
sort() {
this.nodes.sort((a, b) => a.priority - b.priority);
}
isEmpty() {
return !this.nodes.length;
}
}
function dijkstra(graph, start) {
const distances = {};
const previous = {};
const pq = new PriorityQueue();
// Initialize distances and previous
for (let node in graph) {
if (node === start) {
distances[node] = 0;
pq.enqueue(0, node);
} else {
distances[node] = Infinity;
pq.enqueue(Infinity, node);
}
previous[node] = null;
}
while (!pq.isEmpty()) {
const { key: currentNode } = pq.dequeue();
for (let neighbor in graph[currentNode]) {
let alt = distances[currentNode] + graph[currentNode][neighbor];
if (alt < distances[neighbor]) {
distances[neighbor] = alt;
previous[neighbor] = currentNode;
pq.enqueue(alt, neighbor);
}
}
}
return { distances, previous };
}
🛠️ Example Usage:
const graph = {
A: { B: 5, C: 1 },
B: { A: 5, C: 2, D: 1 },
C: { A: 1, B: 2, D: 4, E: 8 },
D: { B: 1, C: 4, E: 3, F: 6 },
E: { C: 8, D: 3 },
F: { D: 6 }
};
const result = dijkstra(graph, 'A');
console.log("Distances from A:", result.distances);
console.log("Previous nodes:", result.previous);
📌 Output Example:
Distances from A:
{ A: 0, B: 3, C: 1, D: 4, E: 7, F: 10 }
Previous nodes:
{ A: null, B: 'C', C: 'A', D: 'B', E: 'D', F: 'D' }
➕ Optional: Find Shortest Path Function
function reconstructPath(previous, end) {
let path = [];
while (end) {
path.unshift(end);
end = previous[end];
}
return path;
}
// Example:
const shortestPath = reconstructPath(result.previous, 'F');
console.log("Shortest path from A to F:", shortestPath);
Let me know if you want this algorithm adapted for a grid, a graph with coordinates, or visualized in a browser!