
Problem
Solution
Submissions
Shortest Path in a Graph
Certification: Advanced Level
Accuracy: 100%
Submissions: 3
Points: 15
Write a Python function that implements the Bellman-Ford algorithm to find the shortest path from a source vertex to all other vertices in a weighted graph. The graph may contain negative weight edges, but not negative weight cycles.
Example 1
- Input: Edges = [(0, 1, 5), (0, 2, 4), (1, 3, 3), (2, 1, -6), (2, 3, 5)], Source = 0, Vertices = 4
- Output: [0, -2, 4, 1]
- Explanation:
- Step 1: Initialize distances [0, inf, inf, inf].
- Step 2: Relax all edges (V-1) times.
- Step 3: Final distances [0, -2, 4, 1].
Example 2
- Input: Edges = [(0, 1, 4), (0, 2, 2), (1, 2, 3), (1, 3, 2), (1, 4, 3), (2, 3, 1), (3, 4, 5)], Source = 0, Vertices = 5
- Output: [0, 4, 2, 3, 7]
- Explanation:
- Step 1: Initialize distances [0, inf, inf, inf, inf].
- Step 2: Relax all edges (V-1) times.
- Step 3: Final distances [0, 4, 2, 3, 7].
Constraints
- 1 ≤ number of vertices ≤ 10^3
- 0 ≤ number of edges ≤ 10^4
- -10^3 ≤ edge weights ≤ 10^3
- Graph may contain negative weight edges but not negative weight cycles
- Time Complexity: O(V * E), where V is the number of vertices and E is the number of edges
- 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 distance to vertices as infinity and distance to source as 0
- Relax all edges V-1 times, where V is the number of vertices
- For each edge (u, v) with weight w, if distance[u] + w < distance[v], update distance[v]
- Check for negative weight cycles by attempting to relax edges one more time
- Return the distance array containing shortest distances to all vertices from source