From dbeacd4e176bdc3b930f554640ac07aea6b30604 Mon Sep 17 00:00:00 2001 From: arpanjain97 Date: Thu, 12 Oct 2017 17:20:34 +0530 Subject: [PATCH] Add Bellman-Ford Algorithm --- Dynamic Programming/Bellman-Ford.cpp | 112 +++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 Dynamic Programming/Bellman-Ford.cpp diff --git a/Dynamic Programming/Bellman-Ford.cpp b/Dynamic Programming/Bellman-Ford.cpp new file mode 100644 index 000000000..83d2aead0 --- /dev/null +++ b/Dynamic Programming/Bellman-Ford.cpp @@ -0,0 +1,112 @@ +#include +#include + +using namespace std; + +//Wrapper class for storing an edge +class Edge{ + public: int src,dst,weight; +}; + +//Wrapper class for storing a graph +class Graph{ + public: + int vertexNum,edgeNum; + Edge* edges; + + //Constructs a graph with V vertices and E edges + Graph(int V,int E){ + this->vertexNum = V; + this->edgeNum = E; + this->edges =(Edge*) malloc(E * sizeof(Edge)); + } + + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight){ + static int edgeInd = 0; + if(edgeInd < this->edgeNum){ + Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + this->edges[edgeInd++] = newEdge; + } + + } + +}; + +//Utility function to print distances +void print(int dist[], int V){ + cout<<"\nVertex Distance"<>V; + cout<<"Enter number of edges: "; + cin>>E; + Graph G(V,E); + for(int i=0; i>src; + cout<<"Enter destination: "; + cin>>dst; + cout<<"Enter weight: "; + cin>>weight; + G.addEdge(src, dst, weight); + } + cout<<"\nEnter source: "; + cin>>gsrc; + BellmanFord(G,gsrc); + + return 0; +}