From 929c1366a00cd5bf59bedf296cfd55566580f4e1 Mon Sep 17 00:00:00 2001 From: Vivek Bisht <68698730+vivekbisht111@users.noreply.github.com> Date: Sat, 20 Mar 2021 20:38:19 +0530 Subject: [PATCH] added bellman-ford for c++ (#115) --- graphs/README.md | 3 +- graphs/c-or-cpp/bellman-ford.cpp | 92 ++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 graphs/c-or-cpp/bellman-ford.cpp diff --git a/graphs/README.md b/graphs/README.md index edddf0fc..3f2ec6f4 100644 --- a/graphs/README.md +++ b/graphs/README.md @@ -3,5 +3,4 @@ ### C or C++ 1. [Kruskal Algorithm](c-or-cpp/kruskal-algorithm.cpp) - - +2. [Bellman Ford Algorithm](c-or-cpp/bellman-ford.cpp) diff --git a/graphs/c-or-cpp/bellman-ford.cpp b/graphs/c-or-cpp/bellman-ford.cpp new file mode 100644 index 00000000..12890e35 --- /dev/null +++ b/graphs/c-or-cpp/bellman-ford.cpp @@ -0,0 +1,92 @@ +//Bellman Ford Algorithm +#include +using namespace std; + + +bool bellman_ford(vector>graph,int V,int s,vector&dist) +{ + + //no. of edges + int n = graph.size(); + for(int i=0;i(graph[j]); + int dest = get<1>(graph[j]); + int weight = get<2>(graph[j]); + + if(dist[src]!=INT_MAX && dist[dest]>dist[src]+weight) + { + dist[dest] = dist[src]+weight; + } + } + } + + //The algorithm works fine with negative edges but does not work with negative weight cycles + //thus checking for any negative weight cycles... + + for(int i=0;i(graph[i]); + int dest = get<1>(graph[i]); + int weight = get<2>(graph[i]); + + if(dist[src]!=INT_MAX && dist[dest]>dist[src]+weight) + { + cout<<"Negative weight cycle detected..\n"; + return false; + } + } + + return true; + +} + + +int main() +{ + //no. of vertices(V) & source(s) + int V = 6, s=0; + + //graph containing all the weighted edges.. + vector>graph; + + //inserting an edge with : + //src = 0 + //dest = 1 + // weight = 10 + graph.push_back(make_tuple(0,1,10)); + graph.push_back(make_tuple(0,2,8)); + graph.push_back(make_tuple(1,4,2)); + graph.push_back(make_tuple(2,3,1)); + graph.push_back(make_tuple(3,1,-4)); + graph.push_back(make_tuple(3,4,-1)); + graph.push_back(make_tuple(4,5,-2)); + graph.push_back(make_tuple(5,1,1)); + + //vector to store distances of all vertices from source(s) + vectordist; + bool neg = bellman_ford(graph,V,s,dist); + + //if no negative weigth cycle is found... + if(neg) + { + cout<<"vertex Dist from Source\n"; + for(int i=0;i