diff --git a/Greedy Algorithms/Dijkstra.cpp b/Greedy Algorithms/Dijkstra.cpp index e53f227c0..5e6d716b6 100644 --- a/Greedy Algorithms/Dijkstra.cpp +++ b/Greedy Algorithms/Dijkstra.cpp @@ -1,107 +1,152 @@ -#include -#include +#include +#include using namespace std; //Wrapper class for storing a graph -class Graph{ - public: - int vertexNum; - int** edges; +class Graph +{ +public: + int vertexNum; + int **edges; - //Constructs a graph with V vertices and E edges - Graph(int V){ - this->vertexNum = V; - this->edges =(int**) malloc(V * sizeof(int*)); - for(int i=0; iedges[i] = (int*) calloc(V, sizeof(int)); - - } + //Constructs a graph with V vertices and E edges + Graph(const int V) + { + + // initializes the array edges. + this->edges = new int*[V]; + for (int i = 0; i < V; i++) + { + edges[i] = new int[V]; + } + + // fills the array with zeros. + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + edges[i][j] = 0; + } + } + + this->vertexNum = V; + + } + + //Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + this->edges[src][dst] = weight; + } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight){ - this->edges[src][dst] = weight; - } - }; //Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], bool vset[], int V){ - int minVal = INT_MAX, minInd; - for(int i=0; i>V; - cout<<"Enter number of edges: "; - cin>>E; - Graph G(V); - 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; - Dijkstra(G,gsrc); +int main() +{ + int V,E,gsrc; + int src,dst,weight; + cout<<"Enter number of vertices: "; + cin>>V; + cout<<"Enter number of edges: "; + cin>>E; + Graph G(V); + for(int i=0; i>src; + cout<<"Enter destination: "; + cin>>dst; + cout<<"Enter weight: "; + cin>>weight; - return 0; + // makes sure source and destionation are in the proper bounds. + if (src >= 0 && src < V && dst >= 0 && dst < V) + { + G.addEdge(src, dst, weight); + } + else + { + cout << "source and/or destination out of bounds" << endl; + i--; + continue; + } + } + cout<<"\nEnter source:"; + cin>>gsrc; + Dijkstra(G,gsrc); + + return 0; }