From f2b57ac058b8794091f3a6c8afd46213813c1b14 Mon Sep 17 00:00:00 2001 From: Amisha Sahu <58816552+Amisha328@users.noreply.github.com> Date: Sat, 7 Oct 2023 14:39:05 +0530 Subject: [PATCH] Add Bellman Ford Algorithm in C++ Given a weighted, directed, and connected graph of V vertices and E edges, Find the shortest distance of all the vertices from the source vertex S. If vertices can't be reached from the S then mark the distance as 10^8. Note: If the Graph contains a negative cycle then return an array consisting of only -1. --- 25-Graph Theory/BellmanFord_Algorithm.cpp | 68 +++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 25-Graph Theory/BellmanFord_Algorithm.cpp diff --git a/25-Graph Theory/BellmanFord_Algorithm.cpp b/25-Graph Theory/BellmanFord_Algorithm.cpp new file mode 100644 index 0000000..138ad83 --- /dev/null +++ b/25-Graph Theory/BellmanFord_Algorithm.cpp @@ -0,0 +1,68 @@ +// Distance from the Source (Bellman-Ford Algorithm) + +#include +using namespace std; + +class Solution{ + public: + // TC-> O(V-1) * O(E) | SC-> O(V) + vector bellman_ford(int V, vector>& edges, int S) { + vector 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> adj; + int i=0; + while (i++> u >> v >> w; + vector t1; + t1.push_back(u); + t1.push_back(v); + t1.push_back(w); + adj.push_back(t1); + } + int S; + cin>>S; + + Solution obj; + vector res = obj.bellman_ford(V, adj, S); + + for(int i=0; i