βΉοΈ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.finalroundai.com/articles/bellman-ford-algorithm |
| Last Crawled | 2026-04-02 11:14:53 (5 days ago) |
| First Indexed | 2025-08-03 19:13:25 (8 months ago) |
| HTTP Status Code | 200 |
| Meta Title | Bellman Ford Algorithm (With Visualization and Code Examples) |
| Meta Description | Learn how to implement the Bellman Ford algorithm in Python, C++, and Java with complete code examples and handle negative edge weights in graph paths. |
| Meta Canonical | null |
| Boilerpipe Text | Finding the shortest path between two points might seem straightforward, but what happens when some paths have negative weights? This is where the Bellman Ford Algorithm becomes your best friend, offering a reliable solution that many other shortest-path algorithms simply can't handle.
Problem Statement
The Bellman Ford Algorithm finds the shortest path from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, it can handle graphs with negative edge weights and can detect negative weight cycles.
Given a weighted directed graph with V vertices and E edges, and a source vertex, we need to:
Find the shortest distance from the source to all other vertices
Detect if there's a negative weight cycle in the graph
For example, consider a graph with vertices A, B, C, D and edges:
A to B: weight 4
A to C: weight 2
C to B: weight -3
B to D: weight 3
C to D: weight 4
Starting from vertex A, the shortest path to D would be A β C β B β D with total weight 2 + (-3) + 3 = 2, not the direct path A β C β D with weight 6.
Brute Force Approach
Explanation
The brute force approach to finding shortest paths would be to examine every possible path from the source to each destination vertex. This means generating all possible sequences of vertices and calculating their total weights.
However, this approach is extremely inefficient. For a graph with V vertices, there could be up to V! different paths to explore, leading to exponential time complexity. In practice, this becomes impossible even for small graphs.
The Bellman Ford algorithm itself is actually an optimized solution compared to this brute force method. It uses dynamic programming principles to avoid recalculating paths repeatedly.
Code (Python)
def brute_force_shortest_path(graph, source, vertices):
"""
Brute force approach - generates all possible paths (impractical for real use)
This is just for educational purposes to show why we need better algorithms
"""
import itertools
# Dictionary to store shortest distances
shortest_distances = {v: float('inf') for v in vertices}
shortest_distances[source] = 0
# Generate all possible permutations of vertices (excluding source)
other_vertices = [v for v in vertices if v != source]
# Check all possible path lengths (1 to V-1)
for path_length in range(1, len(vertices)):
# Generate all permutations of given length
for path_vertices in itertools.permutations(other_vertices, path_length):
# Create complete path starting from source
complete_path = [source] + list(path_vertices)
# Calculate path weight
current_weight = 0
valid_path = True
for i in range(len(complete_path) - 1):
current_vertex = complete_path[i]
next_vertex = complete_path[i + 1]
# Check if edge exists
if next_vertex in graph.get(current_vertex, {}):
current_weight += graph[current_vertex][next_vertex]
else:
valid_path = False
break
# Update shortest distance if this path is better
if valid_path:
destination = complete_path[-1]
shortest_distances[destination] = min(
shortest_distances[destination],
current_weight
)
return shortest_distances
# Example usage
graph = {
'A': {'B': 4, 'C': 2},
'B': {'D': 3},
'C': {'B': -3, 'D': 4},
'D': {}
}
vertices = ['A', 'B', 'C', 'D']
result = brute_force_shortest_path(graph, 'A', vertices)
print("Shortest distances:", result)
Code (C++)
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <climits>
#include <string>
class BruteForceShortestPath {
public:
// Generate all permutations and find shortest paths
std::unordered_map<std::string, int> findShortestPaths(
std::unordered_map<std::string, std::unordered_map<std::string, int>>& graph,
std::string source,
std::vector<std::string>& vertices) {
// Initialize distances
std::unordered_map<std::string, int> shortestDistances;
for (const std::string& vertex : vertices) {
shortestDistances[vertex] = INT_MAX;
}
shortestDistances[source] = 0;
// Get vertices other than source
std::vector<std::string> otherVertices;
for (const std::string& vertex : vertices) {
if (vertex != source) {
otherVertices.push_back(vertex);
}
}
// Try all possible permutations
do {
for (int pathLength = 1; pathLength <= otherVertices.size(); pathLength++) {
// Create path starting from source
std::vector<std::string> currentPath = {source};
for (int i = 0; i < pathLength; i++) {
currentPath.push_back(otherVertices[i]);
}
// Calculate path weight
int currentWeight = 0;
bool validPath = true;
for (int i = 0; i < currentPath.size() - 1; i++) {
std::string currentVertex = currentPath[i];
std::string nextVertex = currentPath[i + 1];
// Check if edge exists
if (graph[currentVertex].find(nextVertex) != graph[currentVertex].end()) {
currentWeight += graph[currentVertex][nextVertex];
} else {
validPath = false;
break;
}
}
// Update shortest distance
if (validPath) {
std::string destination = currentPath.back();
shortestDistances[destination] = std::min(
shortestDistances[destination],
currentWeight
);
}
}
} while (std::next_permutation(otherVertices.begin(), otherVertices.end()));
return shortestDistances;
}
};
int main() {
// Example usage
std::unordered_map<std::string, std::unordered_map<std::string, int>> graph = {
{"A", {{"B", 4}, {"C", 2}}},
{"B", {{"D", 3}}},
{"C", {{"B", -3}, {"D", 4}}},
{"D", {}}
};
std::vector<std::string> vertices = {"A", "B", "C", "D"};
BruteForceShortestPath solver;
auto result = solver.findShortestPaths(graph, "A", vertices);
std::cout << "Shortest distances:\n";
for (const auto& pair : result) {
std::cout << pair.first << ": " << pair.second << "\n";
}
return 0;
}
Code (Java)
import java.util.*;
public class BruteForceShortestPath {
// Method to generate permutations and find shortest paths
public Map<String, Integer> findShortestPaths(
Map<String, Map<String, Integer>> graph,
String source,
List<String> vertices) {
// Initialize distances
Map<String, Integer> shortestDistances = new HashMap<>();
for (String vertex : vertices) {
shortestDistances.put(vertex, Integer.MAX_VALUE);
}
shortestDistances.put(source, 0);
// Get vertices other than source
List<String> otherVertices = new ArrayList<>();
for (String vertex : vertices) {
if (!vertex.equals(source)) {
otherVertices.add(vertex);
}
}
// Generate all permutations
generatePermutations(otherVertices, 0, graph, source, shortestDistances);
return shortestDistances;
}
// Helper method to generate permutations
private void generatePermutations(List<String> vertices, int start,
Map<String, Map<String, Integer>> graph,
String source,
Map<String, Integer> shortestDistances) {
if (start == vertices.size()) {
// Try different path lengths
for (int pathLength = 1; pathLength <= vertices.size(); pathLength++) {
// Create path starting from source
List<String> currentPath = new ArrayList<>();
currentPath.add(source);
for (int i = 0; i < pathLength; i++) {
currentPath.add(vertices.get(i));
}
// Calculate path weight
int currentWeight = 0;
boolean validPath = true;
for (int i = 0; i < currentPath.size() - 1; i++) {
String currentVertex = currentPath.get(i);
String nextVertex = currentPath.get(i + 1);
// Check if edge exists
if (graph.get(currentVertex) != null &&
graph.get(currentVertex).containsKey(nextVertex)) {
currentWeight += graph.get(currentVertex).get(nextVertex);
} else {
validPath = false;
break;
}
}
// Update shortest distance
if (validPath) {
String destination = currentPath.get(currentPath.size() - 1);
shortestDistances.put(destination,
Math.min(shortestDistances.get(destination), currentWeight));
}
}
return;
}
// Generate permutations
for (int i = start; i < vertices.size(); i++) {
Collections.swap(vertices, start, i);
generatePermutations(vertices, start + 1, graph, source, shortestDistances);
Collections.swap(vertices, start, i); // backtrack
}
}
public static void main(String[] args) {
// Example usage
Map<String, Map<String, Integer>> graph = new HashMap<>();
graph.put("A", Map.of("B", 4, "C", 2));
graph.put("B", Map.of("D", 3));
graph.put("C", Map.of("B", -3, "D", 4));
graph.put("D", new HashMap<>());
List<String> vertices = Arrays.asList("A", "B", "C", "D");
BruteForceShortestPath solver = new BruteForceShortestPath();
Map<String, Integer> result = solver.findShortestPaths(graph, "A", vertices);
System.out.println("Shortest distances:");
for (Map.Entry<String, Integer> entry : result.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Conclusion
β
The Bellman Ford Algorithm showcases the importance of choosing the right approach for specific problems. While a brute force method might seem straightforward, it quickly becomes impractical due to its exponential time complexity.
The Bellman Ford Algorithm efficiently solves the single-source shortest path problem in O(V Γ E) time, making it suitable for real-world applications. Its ability to handle negative weights and detect negative cycles makes it more versatile than algorithms like Dijkstra's, though at the cost of higher time complexity.
Learning to optimize solutions like this teaches us to think about edge cases (like negative weights) and trade-offs between different algorithmic approaches. This skill becomes invaluable when tackling complex programming challenges and building efficient systems in software development. |
| Markdown | 
[](https://www.finalroundai.com/)

[](https://www.finalroundai.com/)
- [Interview Copilot](https://www.finalroundai.com/interview-copilot)
- [AI Application](https://www.finalroundai.com/articles/bellman-ford-algorithm)
- [AI Mock Interview](https://www.finalroundai.com/ai-mock-interview)
- [Pricing](https://www.finalroundai.com/articles/bellman-ford-algorithm)
- [Resources](https://www.finalroundai.com/articles/bellman-ford-algorithm)
Resume Creation Tools
[Recruiters Hotline](https://www.finalroundai.com/ai-tools/chat-with-recruiters)
[Resume Checker](https://www.finalroundai.com/ai-tools/resume-checker)
[Cover Letter Generator](https://www.finalroundai.com/ai-tools/cover-letter-generator)
Career Guidance Tools
[AI Career Coach](https://www.finalroundai.com/ai-tools/career-coach)
[LinkedIn Profile Optimizer](https://www.finalroundai.com/ai-tools/linkedin-profile-optimizer)
[LinkedIn Resume Builder](https://www.finalroundai.com/ai-tools/linkedin-resume-builder)
Support
[Guides](https://www.finalroundai.com/guide)
[Blog](https://www.finalroundai.com/blog)
[Articles](https://www.finalroundai.com/articles)

Final Round AI gave me the edge I needed to break into product management. The AI Interview Copilot was super helpful.


Michael Johnson
AI Product Manager of Google
Resume Creation Tools
[Recruiters Hotline](https://www.finalroundai.com/ai-tools/chat-with-recruiters)
[Resume Checker](https://www.finalroundai.com/ai-tools/resume-checker)
[Cover Letter Generator](https://www.finalroundai.com/ai-tools/cover-letter-generator)
Career Guidance Tools
[AI Career Coach](https://www.finalroundai.com/ai-tools/career-coach)
[LinkedIn Profile Optimizer](https://www.finalroundai.com/ai-tools/linkedin-profile-optimizer)
[LinkedIn Resume Builder](https://www.finalroundai.com/ai-tools/linkedin-resume-builder)
Support
[Guides](https://www.finalroundai.com/guide)
[Blog](https://www.finalroundai.com/blog)
[Articles](https://www.finalroundai.com/articles)
- [Question Bank](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[All Articles](https://www.finalroundai.com/articles)
[Data Structures](https://www.finalroundai.com/article-category/data-structures)
# Bellman Ford Algorithm (With Visualization and Code Examples)

Written by
Raj Aryan

Raj Aryan
Raj Aryan is passionate about breaking down complex DSA concepts and making coding feel approachable for everyone. With over 500 problems solved on LeetCode, two hackathon wins under his belt, and a 3-star rating on CodeChef, he enjoys helping others level up their programming skills.
[All articles byRaj Aryan](https://www.finalroundai.com/article-author/raj-aryan)
Edited by
Kaustubh Saini

Kaustubh Saini
Kaustubh Saini writes about software development in a way thatβs easy to follow and genuinely helpful. He breaks down complex topics-from AI to the latest in tech-so they actually make sense. His goal is simple: help others learn, stay curious, and keep up with a fast-changing world.
[All articles byKaustubh Saini](https://www.finalroundai.com/article-author/kaustubh-saini)
Last updated on
July 21, 2025
[Email](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[Facebook](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[X](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[Whatsapp](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[LinkedIn](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[Telegram](https://www.finalroundai.com/articles/bellman-ford-algorithm)
[Reddit](https://www.finalroundai.com/articles/bellman-ford-algorithm)
Finding the shortest path between two points might seem straightforward, but what happens when some paths have negative weights? This is where the Bellman Ford Algorithm becomes your best friend, offering a reliable solution that many other shortest-path algorithms simply can't handle.

## **Problem Statement**
The Bellman Ford Algorithm finds the shortest path from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, it can handle graphs with negative edge weights and can detect negative weight cycles.
Given a weighted directed graph with V vertices and E edges, and a source vertex, we need to:
1. Find the shortest distance from the source to all other vertices
2. Detect if there's a negative weight cycle in the graph
For example, consider a graph with vertices A, B, C, D and edges:
- A to B: weight 4
- A to C: weight 2
- C to B: weight -3
- B to D: weight 3
- C to D: weight 4
Starting from vertex A, the shortest path to D would be A β C β B β D with total weight 2 + (-3) + 3 = 2, not the direct path A β C β D with weight 6.
## **Brute Force Approach**
### **Explanation**
The brute force approach to finding shortest paths would be to examine every possible path from the source to each destination vertex. This means generating all possible sequences of vertices and calculating their total weights.
However, this approach is extremely inefficient. For a graph with V vertices, there could be up to V! different paths to explore, leading to exponential time complexity. In practice, this becomes impossible even for small graphs.
The Bellman Ford algorithm itself is actually an optimized solution compared to this brute force method. It uses dynamic programming principles to avoid recalculating paths repeatedly.
### **Code (Python)**
```
def brute_force_shortest_path(graph, source, vertices):
"""
Brute force approach - generates all possible paths (impractical for real use)
This is just for educational purposes to show why we need better algorithms
"""
import itertools
# Dictionary to store shortest distances
shortest_distances = {v: float('inf') for v in vertices}
shortest_distances[source] = 0
# Generate all possible permutations of vertices (excluding source)
other_vertices = [v for v in vertices if v != source]
# Check all possible path lengths (1 to V-1)
for path_length in range(1, len(vertices)):
# Generate all permutations of given length
for path_vertices in itertools.permutations(other_vertices, path_length):
# Create complete path starting from source
complete_path = [source] + list(path_vertices)
# Calculate path weight
current_weight = 0
valid_path = True
for i in range(len(complete_path) - 1):
current_vertex = complete_path[i]
next_vertex = complete_path[i + 1]
# Check if edge exists
if next_vertex in graph.get(current_vertex, {}):
current_weight += graph[current_vertex][next_vertex]
else:
valid_path = False
break
# Update shortest distance if this path is better
if valid_path:
destination = complete_path[-1]
shortest_distances[destination] = min(
shortest_distances[destination],
current_weight
)
return shortest_distances
# Example usage
graph = {
'A': {'B': 4, 'C': 2},
'B': {'D': 3},
'C': {'B': -3, 'D': 4},
'D': {}
}
vertices = ['A', 'B', 'C', 'D']
result = brute_force_shortest_path(graph, 'A', vertices)
print("Shortest distances:", result)
```
### **Code (C++)**
```
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <climits>
#include <string>
class BruteForceShortestPath {
public:
// Generate all permutations and find shortest paths
std::unordered_map<std::string, int> findShortestPaths(
std::unordered_map<std::string, std::unordered_map<std::string, int>>& graph,
std::string source,
std::vector<std::string>& vertices) {
// Initialize distances
std::unordered_map<std::string, int> shortestDistances;
for (const std::string& vertex : vertices) {
shortestDistances[vertex] = INT_MAX;
}
shortestDistances[source] = 0;
// Get vertices other than source
std::vector<std::string> otherVertices;
for (const std::string& vertex : vertices) {
if (vertex != source) {
otherVertices.push_back(vertex);
}
}
// Try all possible permutations
do {
for (int pathLength = 1; pathLength <= otherVertices.size(); pathLength++) {
// Create path starting from source
std::vector<std::string> currentPath = {source};
for (int i = 0; i < pathLength; i++) {
currentPath.push_back(otherVertices[i]);
}
// Calculate path weight
int currentWeight = 0;
bool validPath = true;
for (int i = 0; i < currentPath.size() - 1; i++) {
std::string currentVertex = currentPath[i];
std::string nextVertex = currentPath[i + 1];
// Check if edge exists
if (graph[currentVertex].find(nextVertex) != graph[currentVertex].end()) {
currentWeight += graph[currentVertex][nextVertex];
} else {
validPath = false;
break;
}
}
// Update shortest distance
if (validPath) {
std::string destination = currentPath.back();
shortestDistances[destination] = std::min(
shortestDistances[destination],
currentWeight
);
}
}
} while (std::next_permutation(otherVertices.begin(), otherVertices.end()));
return shortestDistances;
}
};
int main() {
// Example usage
std::unordered_map<std::string, std::unordered_map<std::string, int>> graph = {
{"A", {{"B", 4}, {"C", 2}}},
{"B", {{"D", 3}}},
{"C", {{"B", -3}, {"D", 4}}},
{"D", {}}
};
std::vector<std::string> vertices = {"A", "B", "C", "D"};
BruteForceShortestPath solver;
auto result = solver.findShortestPaths(graph, "A", vertices);
std::cout << "Shortest distances:\n";
for (const auto& pair : result) {
std::cout << pair.first << ": " << pair.second << "\n";
}
return 0;
}
```
### **Code (Java)**
```
import java.util.*;
public class BruteForceShortestPath {
// Method to generate permutations and find shortest paths
public Map<String, Integer> findShortestPaths(
Map<String, Map<String, Integer>> graph,
String source,
List<String> vertices) {
// Initialize distances
Map<String, Integer> shortestDistances = new HashMap<>();
for (String vertex : vertices) {
shortestDistances.put(vertex, Integer.MAX_VALUE);
}
shortestDistances.put(source, 0);
// Get vertices other than source
List<String> otherVertices = new ArrayList<>();
for (String vertex : vertices) {
if (!vertex.equals(source)) {
otherVertices.add(vertex);
}
}
// Generate all permutations
generatePermutations(otherVertices, 0, graph, source, shortestDistances);
return shortestDistances;
}
// Helper method to generate permutations
private void generatePermutations(List<String> vertices, int start,
Map<String, Map<String, Integer>> graph,
String source,
Map<String, Integer> shortestDistances) {
if (start == vertices.size()) {
// Try different path lengths
for (int pathLength = 1; pathLength <= vertices.size(); pathLength++) {
// Create path starting from source
List<String> currentPath = new ArrayList<>();
currentPath.add(source);
for (int i = 0; i < pathLength; i++) {
currentPath.add(vertices.get(i));
}
// Calculate path weight
int currentWeight = 0;
boolean validPath = true;
for (int i = 0; i < currentPath.size() - 1; i++) {
String currentVertex = currentPath.get(i);
String nextVertex = currentPath.get(i + 1);
// Check if edge exists
if (graph.get(currentVertex) != null &&
graph.get(currentVertex).containsKey(nextVertex)) {
currentWeight += graph.get(currentVertex).get(nextVertex);
} else {
validPath = false;
break;
}
}
// Update shortest distance
if (validPath) {
String destination = currentPath.get(currentPath.size() - 1);
shortestDistances.put(destination,
Math.min(shortestDistances.get(destination), currentWeight));
}
}
return;
}
// Generate permutations
for (int i = start; i < vertices.size(); i++) {
Collections.swap(vertices, start, i);
generatePermutations(vertices, start + 1, graph, source, shortestDistances);
Collections.swap(vertices, start, i); // backtrack
}
}
public static void main(String[] args) {
// Example usage
Map<String, Map<String, Integer>> graph = new HashMap<>();
graph.put("A", Map.of("B", 4, "C", 2));
graph.put("B", Map.of("D", 3));
graph.put("C", Map.of("B", -3, "D", 4));
graph.put("D", new HashMap<>());
List<String> vertices = Arrays.asList("A", "B", "C", "D");
BruteForceShortestPath solver = new BruteForceShortestPath();
Map<String, Integer> result = solver.findShortestPaths(graph, "A", vertices);
System.out.println("Shortest distances:");
for (Map.Entry<String, Integer> entry : result.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
## **Conclusion**β
The Bellman Ford Algorithm showcases the importance of choosing the right approach for specific problems. While a brute force method might seem straightforward, it quickly becomes impractical due to its exponential time complexity.
The Bellman Ford Algorithm efficiently solves the single-source shortest path problem in O(V Γ E) time, making it suitable for real-world applications. Its ability to handle negative weights and detect negative cycles makes it more versatile than algorithms like Dijkstra's, though at the cost of higher time complexity.
Learning to optimize solutions like this teaches us to think about edge cases (like negative weights) and trade-offs between different algorithmic approaches. This skill becomes invaluable when tackling complex programming challenges and building efficient systems in software development.
## FAQs
### TAGS
Linked List
Your resume just got a serious upgrade.
AI-optimized. Recruiter-approved.
[Build your winning resume](https://www.finalroundai.com/ai-resume-builder)
Latest Posts
[Detect a Loop in a Linked List: Codes with Visualization](https://www.finalroundai.com/articles/detect-loop-linked-list)
[Detect a Cycle in a Linked List (With Codes and Visualization)](https://www.finalroundai.com/articles/detect-a-cycle-in-a-linked-list)
[Detect Linked List Cycle Start Node (Floyd's Algorithm)](https://www.finalroundai.com/articles/linked-list-cycle-detection)
[Count Triplets in Sorted Doubly Linked List: O(nΒ²) Solution](https://www.finalroundai.com/articles/count-triplets-sorted-doubly-linked-list)
Your resume just got a serious upgrade.
AI-optimized. Recruiter-approved.
[Build your winning resume](https://www.finalroundai.com/ai-resume-builder)
FAQ Question

FAQ Answer
## Revolutionizing Interview Preparation with AI
[Try it now - Itβs free\!](https://www.finalroundai.com/)
[](https://www.finalroundai.com/)
[](https://www.facebook.com/finalroundai/)[](https://x.com/finalround_ai)[](https://www.instagram.com/finalround_ai/)[](https://www.tiktok.com/@finalroundai.com)[](https://www.youtube.com/@FinalRoundAI)[](https://www.producthunt.com/products/final-round-ai)
***
- Company
- [About](https://www.finalroundai.com/about)
- [Contact Us](https://www.finalroundai.com/contact)
- [Referral Program](https://www.finalroundai.com/referral-program)
- More
- Products
- [Interview Copilot](https://www.finalroundai.com/interview-copilot)
- [AI Mock Interview](https://www.finalroundai.com/ai-mock-interview)
- [AI Salary Calculator](https://www.finalroundai.com/ai-salary-calculator)
- More
- AI Tools
- [Coding Interview Copilot](https://www.finalroundai.com/coding-copilot)
- [AI Career Coach](https://www.finalroundai.com/career-coach)
- [Resume Checker](https://www.finalroundai.com/resume-checker)
- More
- Resources
- [Blog](https://www.finalroundai.com/blog)
- [Hirevue Interviews](https://www.finalroundai.com/hirevue-interview-assistant)
- [Phone Interviews](https://www.finalroundai.com/phone-interview)
- More
***
[Refund Policy](https://www.finalroundai.com/refund-policy)
[Privacy Policy](https://www.finalroundai.com/privacy-policy)
[Terms & Conditions](https://www.finalroundai.com/terms-of-use)
Disclaimer: This platform provides guidance, resources, and support to enhance your job search. However, securing employment within 30 days depends on various factors beyond our control, including market conditions, individual effort, and employer decisions. We do not guarantee job placement within any specific timeframe. Β© 2026 Final Round AI, 188 King St, Unit 402 San Francisco, CA, 94107 |
| Readable Markdown | Finding the shortest path between two points might seem straightforward, but what happens when some paths have negative weights? This is where the Bellman Ford Algorithm becomes your best friend, offering a reliable solution that many other shortest-path algorithms simply can't handle.
## **Problem Statement**
The Bellman Ford Algorithm finds the shortest path from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, it can handle graphs with negative edge weights and can detect negative weight cycles.
Given a weighted directed graph with V vertices and E edges, and a source vertex, we need to:
1. Find the shortest distance from the source to all other vertices
2. Detect if there's a negative weight cycle in the graph
For example, consider a graph with vertices A, B, C, D and edges:
- A to B: weight 4
- A to C: weight 2
- C to B: weight -3
- B to D: weight 3
- C to D: weight 4
Starting from vertex A, the shortest path to D would be A β C β B β D with total weight 2 + (-3) + 3 = 2, not the direct path A β C β D with weight 6.
## **Brute Force Approach**
### **Explanation**
The brute force approach to finding shortest paths would be to examine every possible path from the source to each destination vertex. This means generating all possible sequences of vertices and calculating their total weights.
However, this approach is extremely inefficient. For a graph with V vertices, there could be up to V! different paths to explore, leading to exponential time complexity. In practice, this becomes impossible even for small graphs.
The Bellman Ford algorithm itself is actually an optimized solution compared to this brute force method. It uses dynamic programming principles to avoid recalculating paths repeatedly.
### **Code (Python)**
`def brute_force_shortest_path(graph, source, vertices):"""Brute force approach - generates all possible paths (impractical for real use)This is just for educational purposes to show why we need better algorithms"""import itertools# Dictionary to store shortest distancesshortest_distances = {v: float('inf') for v in vertices}shortest_distances[source] = 0# Generate all possible permutations of vertices (excluding source)other_vertices = [v for v in vertices if v != source]# Check all possible path lengths (1 to V-1)for path_length in range(1, len(vertices)):# Generate all permutations of given lengthfor path_vertices in itertools.permutations(other_vertices, path_length):# Create complete path starting from sourcecomplete_path = [source] + list(path_vertices)# Calculate path weightcurrent_weight = 0valid_path = Truefor i in range(len(complete_path) - 1):current_vertex = complete_path[i]next_vertex = complete_path[i + 1]# Check if edge existsif next_vertex in graph.get(current_vertex, {}):current_weight += graph[current_vertex][next_vertex]else:valid_path = Falsebreak# Update shortest distance if this path is betterif valid_path:destination = complete_path[-1]shortest_distances[destination] = min(shortest_distances[destination],current_weight)return shortest_distances# Example usagegraph = {'A': {'B': 4, 'C': 2},'B': {'D': 3},'C': {'B': -3, 'D': 4},'D': {}}vertices = ['A', 'B', 'C', 'D']result = brute_force_shortest_path(graph, 'A', vertices)print("Shortest distances:", result)`
### **Code (C++)**
`#include <iostream>#include <vector>#include <unordered_map>#include <algorithm>#include <climits>#include <string>class BruteForceShortestPath {public:// Generate all permutations and find shortest pathsstd::unordered_map<std::string, int> findShortestPaths(std::unordered_map<std::string, std::unordered_map<std::string, int>>& graph,std::string source,std::vector<std::string>& vertices) {// Initialize distancesstd::unordered_map<std::string, int> shortestDistances;for (const std::string& vertex : vertices) {shortestDistances[vertex] = INT_MAX;}shortestDistances[source] = 0;// Get vertices other than sourcestd::vector<std::string> otherVertices;for (const std::string& vertex : vertices) {if (vertex != source) {otherVertices.push_back(vertex);}}// Try all possible permutationsdo {for (int pathLength = 1; pathLength <= otherVertices.size(); pathLength++) {// Create path starting from sourcestd::vector<std::string> currentPath = {source};for (int i = 0; i < pathLength; i++) {currentPath.push_back(otherVertices[i]);}// Calculate path weightint currentWeight = 0;bool validPath = true;for (int i = 0; i < currentPath.size() - 1; i++) {std::string currentVertex = currentPath[i];std::string nextVertex = currentPath[i + 1];// Check if edge existsif (graph[currentVertex].find(nextVertex) != graph[currentVertex].end()) {currentWeight += graph[currentVertex][nextVertex];} else {validPath = false;break;}}// Update shortest distanceif (validPath) {std::string destination = currentPath.back();shortestDistances[destination] = std::min(shortestDistances[destination],currentWeight);}}} while (std::next_permutation(otherVertices.begin(), otherVertices.end()));return shortestDistances;}};int main() {// Example usagestd::unordered_map<std::string, std::unordered_map<std::string, int>> graph = {{"A", {{"B", 4}, {"C", 2}}},{"B", {{"D", 3}}},{"C", {{"B", -3}, {"D", 4}}},{"D", {}}};std::vector<std::string> vertices = {"A", "B", "C", "D"};BruteForceShortestPath solver;auto result = solver.findShortestPaths(graph, "A", vertices);std::cout << "Shortest distances:\n";for (const auto& pair : result) {std::cout << pair.first << ": " << pair.second << "\n";}return 0;}`
### **Code (Java)**
`import java.util.*;public class BruteForceShortestPath {// Method to generate permutations and find shortest pathspublic Map<String, Integer> findShortestPaths(Map<String, Map<String, Integer>> graph,String source,List<String> vertices) {// Initialize distancesMap<String, Integer> shortestDistances = new HashMap<>();for (String vertex : vertices) {shortestDistances.put(vertex, Integer.MAX_VALUE);}shortestDistances.put(source, 0);// Get vertices other than sourceList<String> otherVertices = new ArrayList<>();for (String vertex : vertices) {if (!vertex.equals(source)) {otherVertices.add(vertex);}}// Generate all permutationsgeneratePermutations(otherVertices, 0, graph, source, shortestDistances);return shortestDistances;}// Helper method to generate permutationsprivate void generatePermutations(List<String> vertices, int start,Map<String, Map<String, Integer>> graph,String source,Map<String, Integer> shortestDistances) {if (start == vertices.size()) {// Try different path lengthsfor (int pathLength = 1; pathLength <= vertices.size(); pathLength++) {// Create path starting from sourceList<String> currentPath = new ArrayList<>();currentPath.add(source);for (int i = 0; i < pathLength; i++) {currentPath.add(vertices.get(i));}// Calculate path weightint currentWeight = 0;boolean validPath = true;for (int i = 0; i < currentPath.size() - 1; i++) {String currentVertex = currentPath.get(i);String nextVertex = currentPath.get(i + 1);// Check if edge existsif (graph.get(currentVertex) != null &&graph.get(currentVertex).containsKey(nextVertex)) {currentWeight += graph.get(currentVertex).get(nextVertex);} else {validPath = false;break;}}// Update shortest distanceif (validPath) {String destination = currentPath.get(currentPath.size() - 1);shortestDistances.put(destination,Math.min(shortestDistances.get(destination), currentWeight));}}return;}// Generate permutationsfor (int i = start; i < vertices.size(); i++) {Collections.swap(vertices, start, i);generatePermutations(vertices, start + 1, graph, source, shortestDistances);Collections.swap(vertices, start, i); // backtrack}}public static void main(String[] args) {// Example usageMap<String, Map<String, Integer>> graph = new HashMap<>();graph.put("A", Map.of("B", 4, "C", 2));graph.put("B", Map.of("D", 3));graph.put("C", Map.of("B", -3, "D", 4));graph.put("D", new HashMap<>());List<String> vertices = Arrays.asList("A", "B", "C", "D");BruteForceShortestPath solver = new BruteForceShortestPath();Map<String, Integer> result = solver.findShortestPaths(graph, "A", vertices);System.out.println("Shortest distances:");for (Map.Entry<String, Integer> entry : result.entrySet()) {System.out.println(entry.getKey() + ": " + entry.getValue());}}}`
## **Conclusion**β
The Bellman Ford Algorithm showcases the importance of choosing the right approach for specific problems. While a brute force method might seem straightforward, it quickly becomes impractical due to its exponential time complexity.
The Bellman Ford Algorithm efficiently solves the single-source shortest path problem in O(V Γ E) time, making it suitable for real-world applications. Its ability to handle negative weights and detect negative cycles makes it more versatile than algorithms like Dijkstra's, though at the cost of higher time complexity.
Learning to optimize solutions like this teaches us to think about edge cases (like negative weights) and trade-offs between different algorithmic approaches. This skill becomes invaluable when tackling complex programming challenges and building efficient systems in software development. |
| Shard | 181 (laksa) |
| Root Hash | 8075799420860259781 |
| Unparsed URL | com,finalroundai!www,/articles/bellman-ford-algorithm s443 |