
Problem
Solution
Submissions
Bellman-Ford Algorithm
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to implement the Bellman-Ford algorithm to find the shortest paths from a source vertex to all other vertices in a weighted graph. The graph may contain negative weight edges, but should not contain negative weight cycles.
Example 1
- Input: Number of vertices: 5 Number of edges: 8 Edges and weights: 0 1 -1 0 2 4 1 2 3 1 3 2 1 4 2 3 2 5 3 1 1 4 3 -3 Source vertex: 0
- Output: Vertex Distance from Source: 0 0 1 -1 2 2 3 -2 4 1
- Explanation:
- Step 1: Initialize distances from source to all vertices as infinite, and distance to source itself as 0.
- Step 2: Relax all edges V-1 times, where V is the number of vertices.
- Step 3: For each edge (u, v) with weight w, if distance[u] + w < distance[v], set distance[v] = distance[u] + w.
- Step 4: Check for negative weight cycles. None found in this example.
- Step 5: Return the final distances from the source vertex:
- Distance to vertex 0 (source): 0
- Distance to vertex 1: -1
- Distance to vertex 2: 2
- Distance to vertex 3: -2
- Distance to vertex 4: 1
Example 2
- Input: Number of vertices: 4 Number of edges: 5 Edges and weights: 0 1 1 1 2 -1 2 3 -1 3 0 -1 0 2 4 Source vertex: 0
- Output: Graph contains a negative weight cycle
- Explanation:
- Step 1: Initialize distances from source to all vertices as infinite, and distance to source itself as 0.
- Step 2: Relax all edges V-1 times, where V is the number of vertices.
- Step 3: For each edge (u, v) with weight w, if distance[u] + w < distance[v], set distance[v] = distance[u] + w.
- Step 4: Check for negative weight cycles by attempting to relax edges one more time:
- If any distance can be further reduced, there's a negative weight cycle.
- In this graph, the path 0 → 1 → 2 → 3 → 0 forms a cycle with total weight 1 + (-1) + (-1) + (-1) = -2.
- Step 5: Return that the graph contains a negative weight cycle.
Constraints
- 1 ≤ Number of vertices ≤ 100
- 1 ≤ Number of edges ≤ 1000
- Time Complexity: O(V * E)
- Space Complexity: O(V)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Initialize distances from the source to all vertices as infinite and distance to the source itself as 0.
- Let all edges (V-1) times to find the shortest paths.
- Check for negative weight cycles by relaxing edges one more time.
- If any distance is updated during the V-th relaxation, the graph contains a negative weight cycle.