📖 Scenario: You are working on a navigation system that needs to find the shortest path between cities. Some roads have toll discounts represented as negative weights. You need to handle these negative weights safely.
🎯 Goal: Build a TypeScript program that uses the Bellman Ford algorithm to find the shortest distances from a starting city to all other cities, even when some roads have negative weights.
📋 What You'll Learn
Create an array of edges representing roads with source, destination, and weight
Create a variable for the number of vertices (cities)
Implement the Bellman Ford algorithm to calculate shortest distances
Detect if there is a negative weight cycle
Print the shortest distances or a message if a negative cycle exists
💡 Why This Matters
🌍 Real World
Navigation systems and routing algorithms often need to handle roads with discounts or penalties, which can be modeled as negative weights.
💼 Career
Understanding Bellman Ford is important for software engineers working on graph algorithms, network routing, and optimization problems.
Progress0 / 4 steps
1
Create the graph edges array
Create a variable called edges as an array of objects with these exact entries: {src: 0, dest: 1, weight: 5}, {src: 1, dest: 2, weight: -2}, {src: 2, dest: 3, weight: 3}, {src: 3, dest: 1, weight: 1}, {src: 0, dest: 3, weight: 10}.
DSA Typescript
Hint
Use an array of objects where each object has src, dest, and weight properties.
2
Set the number of vertices
Create a variable called vertices and set it to 4 to represent the number of cities.
DSA Typescript
Hint
Count the unique cities from the edges and assign the number to vertices.
3
Implement the Bellman Ford algorithm
Create a function called bellmanFord that takes edges, vertices, and start as parameters. Inside, create a distances array of length vertices filled with Infinity. Set distances[start] to 0. Use a for loop from 0 to vertices - 1 to relax edges. Then check for negative weight cycles by iterating over edges and returning null if a cycle is found. Otherwise, return distances.
DSA Typescript
Hint
Follow the Bellman Ford steps: initialize distances, relax edges multiple times, then check for negative cycles.
4
Print the shortest distances or negative cycle message
Call bellmanFord(edges, vertices, 0) and store the result in result. If result is null, print "Graph contains a negative weight cycle". Otherwise, print "Shortest distances from vertex 0:" followed by the result array.
DSA Typescript
Hint
Call the function with start vertex 0. Check if the result is null to detect negative cycles. Print the distances array if no cycle.
Practice
(1/5)
1. What is the main advantage of the Bellman-Ford algorithm compared to Dijkstra's algorithm?
easy
A. It uses less memory.
B. It runs faster on all graphs.
C. It can handle graphs with negative weight edges.
D. It only works on directed acyclic graphs.
Solution
Step 1: Understand the limitation of Dijkstra's algorithm
Dijkstra's algorithm cannot correctly handle graphs with negative weight edges because it assumes that once a node's shortest path is found, it cannot be improved.
Step 2: Identify Bellman-Ford's capability
Bellman-Ford algorithm can handle negative weight edges and detect negative weight cycles, making it more versatile for such graphs.
Final Answer:
It can handle graphs with negative weight edges. -> Option C
Quick Check:
Negative weights handled = A [OK]
Hint: Bellman-Ford works with negative edges, Dijkstra doesn't [OK]
Common Mistakes:
Thinking Bellman-Ford is always faster
Believing it uses less memory
Assuming it only works on acyclic graphs
2. Which of the following is the correct TypeScript syntax to initialize the distance array for Bellman-Ford with infinity except the source node set to 0?
easy
A. const dist = new Array(n).fill(Infinity); dist[source] = 0;
B. const dist = Array(n).fill(0); dist[source] = Infinity;
C. const dist = new Array(n).fill(0); dist[source] = 0;
D. const dist = new Array(n).fill(-Infinity); dist[source] = 0;
Solution
Step 1: Initialize distances with Infinity
We start with all distances as Infinity to represent unknown paths, except the source which is 0.
Step 2: Correct syntax for array initialization
Using new Array(n).fill(Infinity) creates an array of size n filled with Infinity, then setting dist[source] = 0 sets the source distance correctly.
Final Answer:
const dist = new Array(n).fill(Infinity); dist[source] = 0; -> Option A
Quick Check:
Initialize with Infinity except source 0 = C [OK]
Hint: Fill array with Infinity, then set source to 0 [OK]
Common Mistakes:
Filling with 0 instead of Infinity
Setting source distance to Infinity
Using -Infinity which is incorrect
3. Consider the following TypeScript code snippet implementing one iteration of edge relaxation in Bellman-Ford:
for (const [u, v, w] of edges) {
if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
console.log(dist);
If edges = [[0,1,4],[1,2,-2],[0,2,5]] and initial dist = [0, Infinity, Infinity], what will be the output after this iteration?