class Graph {
adjacencyList: Map<string, Array<{node: string; weight: number}>> = new Map();
addEdge(u: string, v: string, w: number) {
if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
this.adjacencyList.get(u)!.push({node: v, weight: w});
this.adjacencyList.get(v)!.push({node: u, weight: w});
}
}
function dijkstra(graph: Graph, start: string): Map<string, number> {
const distances = new Map<string, number>();
const visited = new Set<string>();
const nodes = Array.from(graph.adjacencyList.keys());
// Initialize distances
for (const node of nodes) {
distances.set(node, Infinity);
}
distances.set(start, 0);
while (visited.size < nodes.length) {
// Find unvisited node with smallest distance
let currentNode: string | null = null;
let smallestDistance = Infinity;
for (const node of nodes) {
if (!visited.has(node) && distances.get(node)! < smallestDistance) {
smallestDistance = distances.get(node)!;
currentNode = node;
}
}
if (currentNode === null) break; // Remaining nodes unreachable
visited.add(currentNode);
// Update distances for neighbors
for (const neighbor of graph.adjacencyList.get(currentNode)!) {
if (!visited.has(neighbor.node)) {
const newDist = distances.get(currentNode)! + neighbor.weight;
if (newDist < distances.get(neighbor.node)!) {
distances.set(neighbor.node, newDist);
}
}
}
}
return distances;
}
// Driver code
const graph = new Graph();
graph.addEdge('A', 'B', 5);
graph.addEdge('A', 'C', 1);
graph.addEdge('B', 'C', 2);
const shortestDistances = dijkstra(graph, 'A');
for (const [node, dist] of shortestDistances) {
console.log(`${node}: ${dist}`);
}Set distance to start node as zero
for (const node of nodes) { if (!visited.has(node) && distances.get(node)! < smallestDistance) { smallestDistance = distances.get(node)!; currentNode = node; } }
Select unvisited node with smallest known distance
visited.add(currentNode);
Mark current node as visited to avoid revisiting
for (const neighbor of graph.adjacencyList.get(currentNode)!) { if (!visited.has(neighbor.node)) { const newDist = distances.get(currentNode)! + neighbor.weight; if (newDist < distances.get(neighbor.node)!) { distances.set(neighbor.node, newDist); } } }
Update distances for neighbors if shorter path found