class Edge {
constructor(public from: string, public to: string, public weight: number) {}
}
class Graph {
edges: Edge[] = [];
vertices: Set<string> = new Set();
addEdge(from: string, to: string, weight: number) {
this.edges.push(new Edge(from, to, weight));
this.vertices.add(from);
this.vertices.add(to);
}
}
function bellmanFord(graph: Graph, start: string): Map<string, number> | null {
const dist = new Map<string, number>();
// Initialize distances
for (const v of graph.vertices) {
dist.set(v, Infinity);
}
dist.set(start, 0);
const V = graph.vertices.size;
// Relax edges V-1 times
for (let i = 1; i <= V - 1; i++) {
let updated = false;
for (const edge of graph.edges) {
const uDist = dist.get(edge.from)!;
const vDist = dist.get(edge.to)!;
if (uDist !== Infinity && uDist + edge.weight < vDist) {
dist.set(edge.to, uDist + edge.weight);
updated = true;
}
}
if (!updated) break; // No changes, stop early
}
// Check for negative weight cycles
for (const edge of graph.edges) {
const uDist = dist.get(edge.from)!;
const vDist = dist.get(edge.to)!;
if (uDist !== Infinity && uDist + edge.weight < vDist) {
return null; // Negative cycle detected
}
}
return dist;
}
// Driver code
const graph = new Graph();
graph.addEdge('A', 'B', -1);
graph.addEdge('A', 'C', 4);
graph.addEdge('B', 'C', 3);
graph.addEdge('B', 'A', 2);
graph.addEdge('C', 'B', 5);
const distances = bellmanFord(graph, 'A');
if (distances === null) {
console.log('Graph contains a negative weight cycle');
} else {
for (const [vertex, distance] of distances.entries()) {
console.log(`${vertex}: ${distance}`);
}
}
for (const v of graph.vertices) { dist.set(v, Infinity); } dist.set(start, 0);
Initialize all distances to infinity except start node to zero
for (let i = 1; i < V; i++) { for (const edge of graph.edges) { if (uDist !== Infinity && uDist + edge.weight < vDist) { dist.set(edge.to, uDist + edge.weight); updated = true; } } if (!updated) break; }
Relax all edges repeatedly to update shortest distances
for (const edge of graph.edges) { if (uDist !== Infinity && uDist + edge.weight < vDist) { return null; } }
Detect negative weight cycles by checking for further improvements