⬅ Previous Topic
Dijkstra's Algorithm Using Set - Shortest Path in GraphNext Topic ⮕
Shortest Distance in a Binary Maze using BFS⬅ Previous Topic
Dijkstra's Algorithm Using Set - Shortest Path in GraphNext Topic ⮕
Shortest Distance in a Binary Maze using BFSTopic Contents
You are given a weighted, undirected, and connected graph with V
vertices represented using an adjacency list. Each entry adj[i]
contains a list of lists, where each sublist contains two integers j
and weight
, representing an edge from vertex i
to vertex j
with a given weight.
Given a source vertex S
, your task is to find the shortest distances from S
to all other vertices using Dijkstra’s Algorithm and return them as a list.
dist[]
with Infinity
, set dist[S] = 0
.{0, S}
.v
of the current node:dist[u] + weight < dist[v]
, update dist[v]
and add {dist[v], v}
to the queue.dist[]
as the shortest distances from source S
.function dijkstra(V, adj, S) {
const dist = new Array(V).fill(Infinity);
dist[S] = 0;
const minHeap = [[0, S]]; // [distance, vertex]
while (minHeap.length > 0) {
minHeap.sort((a, b) => a[0] - b[0]);
const [d, u] = minHeap.shift();
for (const [v, wt] of adj[u]) {
if (d + wt < dist[v]) {
dist[v] = d + wt;
minHeap.push([dist[v], v]);
}
}
}
return dist;
}
// Example:
const adjList = [
[[1, 1], [2, 4]],
[[0, 1], [2, 2]],
[[0, 4], [1, 2]]
];
console.log("Shortest distances:", dijkstra(3, adjList, 0)); // Output: [0, 1, 3]
⬅ Previous Topic
Dijkstra's Algorithm Using Set - Shortest Path in GraphNext Topic ⮕
Shortest Distance in a Binary Maze using BFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.