Skip to content

Add Bellman Ford Algorithm in C++ #146

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions 25-Graph Theory/BellmanFord_Algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Distance from the Source (Bellman-Ford Algorithm)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a quick introductory sentence above this explaining what this algorithm is before jumping to the solution?


#include<bits/stdc++.h>
using namespace std;

class Solution{
public:
// TC-> O(V-1) * O(E) | SC-> O(V)
vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
vector<int> dist(V, 1e8);
dist[S] = 0;
for(int i = 1; i <= V-1; i++)
{
for(auto it: edges){
int u = it[0];
int v = it[1];
int wt = it[2];

if(dist[u] != 1e8 && dist[u] + wt < dist[v])
dist[v] = dist[u] + wt;
}
}

// do the last relaxation for Vth time
// to check if negative edge cycle exists
for(auto it: edges){
int u = it[0];
int v = it[1];
int wt = it[2];

if(dist[u] != 1e8 && dist[u] + wt < dist[v])
return {-1};
}
return dist;
}
};

int main()
{
int t;
cin >> t;
while (t--) {
int V, E;
cin >> V >> E;
vector<vector<int>> adj;
int i=0;
while (i++<E) {
int u, v, w;
cin >> u >> v >> w;
vector<int> t1;
t1.push_back(u);
t1.push_back(v);
t1.push_back(w);
adj.push_back(t1);
}
int S;
cin>>S;

Solution obj;
vector<int> res = obj.bellman_ford(V, adj, S);

for(int i=0; i<V; i++)
cout<<res[i]<<" ";
cout<<endl;
}

return 0;
}