Distance from the Source (Bellman-Ford Algorithm) | Practice | GeeksforGeeks

Given a weighted, directed and connected graph of V vertices and E edges, Find the shortest distance of all the vertex's from the source vertex S.
Note: The Graph doesn't contain any negative weight cycle.
 
Example 1:
Input:

S = 0
Output:
0 9
Explanation:
Shortest distance of all nodes from
source is printed.

Example 2:
Input:

S = 2
Output:
1 6 0
Explanation:
For nodes 2 to 0, we can follow the path-
2-0. This has a distance of 1.
For nodes 2 to 1, we cam follow the path-
2-0-1, which has a distance of 1+5 = 6,

 
Your Task:
You don't need to read input or print anything. Your task is to complete the function bellman_ford()  which takes number of vertices V and an E sized list of lists of three integers where the three integers are u,v, and w; denoting there's an edge from u to v, which has a weight of w as input parameters and returns a list of integers where the ith integer denotes the distance of ith node from source node. If some node isn't possible to visit, then it's distance should be 100000000(1e8).
 
Expected Time Complexity: O(V*E).
Expected Auxiliary Space: O(V).
 
Constraints:
1  ≤  V  ≤ 500
1  ≤ E  ≤ V*(V-1)
-1000  ≤  adj[i][j]  ≤  1000
0  ≤  S < V
+1
bhardwajji2 weeks ago
vector <int> bellman_ford(int n, vector<vector<int>> adj, int s) {
        vector<int>dist(n,100000000);
        dist[s]=0;
        
        for(int i=0;i<n;i++){
            for(auto it: adj){
                int u=it[0] , v=it[1], d=it[2];
                if(dist[u]!=INT_MAX && dist[u]+d < dist[v])
                    dist[v] = dist[u]+d;
            }
        }
        
        return dist;
        
        
    }
+2
mohdhammadsiddiqui2 months ago
Shortest C++ Solution:-
#include<bits/stdc++.h>class Solution{public:   vector <int> bellman_ford(int N, vector<vector<int>> adj, int source) {   vector<int> distance(N,100000000),empty;   distance[source]=0;   for(int i=1;i<=N-1;i++)        for(auto itr:adj)  if(distance[itr[0]]+itr[2]<distance[itr[1]]) distance[itr[1]]=distance[itr[0]]+itr[2];   for(auto itr:adj) if(distance[itr[0]]+itr[2]<distance[itr[1]]) return empty;       return distance;   }};
 
 
 
0
satyendra yadav 12 months ago
Even dijkstra algorithm would work here because it's explicitly given that graph doesn't contain any negative cycle. But the cavaet here is to use dijkstra without using visited_node info. Refer this video 
+1
gowthamreddyuppunuri2 months ago
Relaxing edges greedily to find the optimal path 
In a graph of N nodes, then in worst case a path contains N-1 edges.
for run a loop for N-1 times
and relax all edges
Point to be noted dijkstra won't work for negative edges in directed graph, but bellmann ford will work but it also fails obviouly in negative weight cycle.
vector <int> bellman_ford(int V, vector<vector<int>> adj, int S) {
        //make edges or use adj list
        const int INF = 1e8;
        vector<int> dist(V,INF);
        dist[S] = 0;//source to source distance is 0
        //Relax all edges N times
        for(int i=0; i<V-1; i++){
           for(auto vec:adj){
               int u = vec[0], v = vec[1], wt = vec[2];
               //Relaxing
               if(dist[v] > dist[u]+wt){
                   dist[v] = dist[u] + wt;
               }
           }
        }
        //check for last to detect negative cycle
        bool ok = true;
        for(int i=0; i<1; i++){
            for(auto vec:adj){
               int u = vec[0], v = vec[1], wt = vec[2];
               //Relaxing
               if(dist[v] > dist[u]+wt){
                   ok = false;
                   break;
               }
           }
           if(!ok){
               break;
           }
        }
        if(ok){
            return dist;
        }
        else{
            cout<<"There is a Negative Cycle!";
            return dist;
        }
    }
+2
badshalaskar3 months ago
Python solution approach:
take a distance array
fill it with 100000000
initiate first node = 0
now run a loop for v-1 times and for each time calculate all the adjacent min distance and store it in array
import collections
class Solution:
    def bellman_ford(self, V, adj, S):
        # initialize all distance = infi
        dist = [100000000]*V
        # initialize the start to start = 0 
        dist[S] = 0
        for i in range(V-1):
            for src, dest, distance in adj:
                dist[dest] = min(dist[dest], dist[src]+distance)
        return dist
+4
sk77887753 months ago
class Solution
{
    static int[] bellman_ford(int V, ArrayList<ArrayList<Integer>> adj, int S)
    {
        // Write your code here
        int[] dist=new int[V];
        Arrays.fill(dist,100000000);
        dist[S]=0;
        for(int i=1;i<=V-1;i++) {
            for(ArrayList<Integer> arr:adj) {
                int u=arr.get(0);
                int v=arr.get(1);
                int w=arr.get(2);
                dist[v]=Math.min(dist[v],dist[u]+w);
            }
        }
        return dist;
    }
}

+1
mayanksamadhiya123455 months ago
vector <int> bellman_ford(int V, vector<vector<int>> adj, int S)    {       int mx=100000000;       vector<int> dist(V,mx);       dist[S]=0;              // start relaxing for n-1 times        // why n-1 time because n-1 is the longest path       // and we will check for n-1 path because thereis -marking so next might be min answer       // adj = [[u,v,w]]       // it[0]=u , it[v]=1 , it[2]=w       for(int i=1;i<=V-1;i++)       {           for(auto it : adj)           {               if(dist[it[0]]+it[2]<dist[it[1]])               {                   dist[it[1]]=dist[it[0]]+it[2];               }           }       }              // after n-1 relaxation check for the negative cycle       int flag=1;       for(auto i : adj)       {           if(dist[i[0]]+i[2]<dist[i[1]])           {               flag=0;               return false;           }       }              vector<int> res;       if(flag==1)       {           return dist;       }   }};
0
shivambhadani1236 months ago
Bellman Ford Algorithm
vector <int> bellman_ford(int V, vector<vector<int>> adj, int S) {
        int inf = 1e8;
        vector<int> dis(V, inf);
        dis[S] = 0;
        for(int i=1; i<=V-1; i++) {
            for(auto& it: adj) {
                if(dis[it[0]]==inf) continue;
                if(dis[it[0]] + it[2] < dis[it[1]]) 
                    dis[it[1]] = dis[it[0]] + it[2];
            }
        }
        return dis;
    }
+1
anutiger6 months ago
simple bellman ford algorithm 
    steps :       1 create a vector of size ret.
       2 give maximum value to all the nodes in  vector except node S
       3 now apply bellman-ford algorithm.           1)check whether the weight to reach node v is greater then weight to reach node u + weight between them.
           2)loop through all the edges
       4 Repeat V times
       5 return the vector.
 
    vector <int> bellman_ford(int V, vector<vector<int>> adj, int S) {
        vector<int> ret(V,100000000);
        ret[S] = 0;
        for(int i = 0 ; i < V; i++){
            for(auto it : adj){
                if(ret[it[0]] != INT_MAX and ret[it[1]]  > ret[it[0]] + it[2]){
                	ret[it[1]] = ret[it[0]] + it[2];
                }
            }
        }
        return ret;
    }
0
rishabsharma6 months ago
vector <int> bellman_ford(int V, vector<vector<int>> adj, int S) {
        // Code here
        
        vector<int> distance(V, 1e8);
        
        distance[S] = 0;
        
        for(int i = 0;i < V-1; i++)
        {
            for(auto &x : adj)
            {
                int u = x[0], v = x[1], wt = x[2];
                
                if(distance[u] + wt < distance[v])
                    distance[v] = distance[u] + wt;
            }
        }
        
        return distance;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.