Tutorialspoint
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)
GraphAlgorithmsCognizantWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize distances from source to all vertices as infinite, and source to 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,w), if distance[u] + w < distance[v], update distance[v].
 Step 4: Check for negative weight cycles by attempting one more relaxation.
 Step 5: If any distance can still be updated, a negative cycle exists.
 Step 6: Return the final distance array or indication of negative cycle.

Submitted Code :