class Graph {
vertices: number;
adjList: Map<number, Array<[number, number]>>;
constructor(vertices: number) {
this.vertices = vertices;
this.adjList = new Map();
for (let i = 0; i < vertices; i++) {
this.adjList.set(i, []);
}
}
addEdge(u: number, v: number, w: number) {
this.adjList.get(u)?.push([v, w]);
}
topologicalSortUtil(v: number, visited: boolean[], stack: number[]) {
visited[v] = true;
for (const [neighbor] of this.adjList.get(v)!) {
if (!visited[neighbor]) {
this.topologicalSortUtil(neighbor, visited, stack);
}
}
stack.push(v); // add node after visiting neighbors
}
shortestPath(start: number): number[] {
const visited = new Array(this.vertices).fill(false);
const stack: number[] = [];
// Step 1: Topological sort
for (let i = 0; i < this.vertices; i++) {
if (!visited[i]) {
this.topologicalSortUtil(i, visited, stack);
}
}
stack.reverse(); // reverse to get correct order
// Step 2: Initialize distances
const dist = new Array(this.vertices).fill(Infinity);
dist[start] = 0;
// Step 3: Relax edges in topological order
for (const u of stack) {
if (dist[u] !== Infinity) {
for (const [v, w] of this.adjList.get(u)!) {
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w; // update shorter distance
}
}
}
}
return dist;
}
}
// Driver code
const g = new Graph(5);
g.addEdge(0, 1, 2);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 1);
g.addEdge(1, 3, 7);
g.addEdge(2, 4, 3);
g.addEdge(3, 4, 1);
const startNode = 0;
const distances = g.shortestPath(startNode);
for (let i = 0; i < distances.length; i++) {
console.log(`Distance from ${startNode} to ${i} is ${distances[i]}`);
}stack.push(v); // add node after visiting neighbors
Add node to stack after all its descendants are visited to get topological order
stack.reverse(); // reverse to get correct order
Reverse stack to get nodes in topological order
Set start node distance to zero
if (dist[u] !== Infinity) {
Only process nodes reachable from start
if (dist[v] > dist[u] + w) {
Relax edge if shorter path found
dist[v] = dist[u] + w; // update shorter distance
Update distance to neighbor
Distance from 0 to 0 is 0
Distance from 0 to 1 is 2
Distance from 0 to 2 is 3
Distance from 0 to 3 is 9
Distance from 0 to 4 is 6