What is the Bellman-Ford algorithm, and how do I implement it in TypeScript?
The Bellman-Ford algorithm computes shortest paths from a single source in a graph with negative weights, unlike Dijkstra's. It’s slower but can handle graphs with negative cycles.
The Bellman-Ford algorithm is a single-source shortest path algorithm, similar to Dijkstra’s algorithm, but with the added ability to handle graphs that contain negative weight edges. While Dijkstra’s algorithm fails with negative weights, Bellman-Ford is designed to detect negative weight cycles and compute the shortest paths even when such cycles exist. The algorithm works by repeatedly relaxing all the edges in the graph over a number of iterations equal to the number of vertices minus one. Relaxing an edge means checking whether the current shortest distance to a destination node can be improved by taking the edge from the source node. After V-1 iterations (where V is the number of vertices), if the distance can still be reduced, a negative cycle is detected. Implementing the Bellman-Ford algorithm in TypeScript involves representing the graph using an edge list and repeatedly relaxing the edges in a loop. While Bellman-Ford runs in O(V * E) time, making it slower than Dijkstra’s O(E + log V), it’s indispensable for scenarios where negative weights and cycles are present, such as in currency arbitrage, routing in packet-switched networks, or other optimization problems.