#include <iostream>
#include <list>
using namespace std;
class edge
{
public:
int dest;
int dist;
edge(int a,int b)
{
dest=a;
dist=b;
}
};
class Graph
{
public:
int v;
list<edge> *adj;
list<int> remEdges;
int *dist;
int *parent;
int src;
Graph(int);
void addEdge(int,int,int);
void printEdges(int);
bool isPresent(int);
int findMin();
void dijkstra(int);
};
Graph::Graph(int v)
{
adj = new list<edge>[v];
this->v=v;
dist=new int(v);
parent=new int(v);
for(int i=0;i<v;i++)
{
remEdges.push_back(i);
dist[i]=INT_MAX;
}
}
bool Graph::isPresent(int num)
{
list<int> :: iterator i;
for(i=remEdges.begin();i!=remEdges.end();i++)
if(num==*i)
return true;
return false;
}
int Graph::findMin()
{
int min=INT_MAX;
int index=-1;
for(int i=0;i<v;i++)
if(dist[i]<min && isPresent(i))
{
min=dist[i];
index=i;
}
return index;
}
void Graph :: addEdge(int i,int j,int k)
{
adj[i].push_back(edge(j,k));
adj[j].push_back(edge(i,k));
}
void Graph :: printEdges(int src)
{
for(int i=0;i<v;i++)
if(i!=src)
cout<<dist[i]<<" ";
}
void Graph::dijkstra(int src)
{
dist[src]=0;
while(!remEdges.empty())
{
int min=findMin();
list<edge> :: iterator i;
for(i=adj[min].begin();i!=adj[min].end();i++)
{
if(isPresent((*i).dest))
{
if(dist[min]+(*i).dist<dist[(*i).dest])
dist[(*i).dest] = dist[min]+(*i).dist;
}
parent[(*i).dest]=min;
}
remEdges.remove(min);
}
}
int main()
{
Graph g(9);
g.addEdge(0, 1, 4);
g.addEdge(0, 7, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 3, 7);
g.addEdge(2, 8, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 5, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 8, 6);
g.addEdge(7, 8, 7);
g.dijkstra(0);
g.printEdges(0);
cout<<endl;
return 0;
}
Code not working for bigger inputs.
I am newbie to algorithms and I wanted to implement dijkstra algorithm through CPP. Spent lot of hours to fix the code.
Its showing correct output during debug mode but it's not working when executed directly from Run button.
I am using DEV C++ to run the code and it is executing fine when the driver function is
int main()
{
Graph g(4);
g.addEdge(0, 1, 24);
g.addEdge(0, 3, 20);
g.addEdge(2, 0, 3);
g.addEdge(3, 2, 12);
g.dijkstra(0);
g.printEdges(0);
cout<<endl;
return 0;
}
But it is not working when I am adding too many edges.
Please help me in this regard.