Reputation: 31
This is my code.. I tried hard to detect the fault but it compiles properly and then gives segmentation fault while executing...
#include<iostream>
#include<string>
using namespace std;
#define infinity 999
#define MAX 10
int min(int dis[],bool vis[],int n);
void print_dij(int dis[],int n);
class graph
{
int g[MAX][MAX];
public:
int n;
graph()
{
n=0;
}
void readgraph();
void printgraph();
void dij();
};
void graph::readgraph()
{
int i,j;
cout<<"\nEnter the no of vertices::";
cin>>n;
cout<<"\nEnter the adjacency matrix::";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<"\n["<<i<<"]["<<j<<"]::";
cin>>g[i][j];
}
}
}
void graph::printgraph()
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cout<<g[i][j];
cout<<"\n";
}
}
void graph::dij()
{
int dis[20],i,j,start,u;
bool vis[20];
cout<<"\nEnter the index number of starting node::";
cin>>start;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(g[i][j]==0)
g[i][j]=infinity;
for(i=0;i<n;i++) //Initialising the arrays dis[] and vis[]
{
dis[i]=infinity;
vis[i]=false;
}
dis[start]=0;
for(i=0;i<n-1;i++) //Finding the shortest path
{
u=min(dis,vis,n);
vis[u]=true;
for(j=0;j<n;j++)
if(!vis[j] && g[u][j] && dis[u]!=infinity && dis[u]+g[u][j]<dis[j])
dis[i]=dis[u]+g[u][j];
}
cout<<"\nThe shortest path is::->>>>>\n";
print_dij(dis,n);
}
int min(int dis[],bool vis[],int n) //To find the vertex with min distance from the source
{
int index,i,min=infinity;
for(i=0;i<n;i++)
if(vis[i]=false && dis[i]<=min)
{
min=dis[i];
index=i;
}
return index;
}
void print_dij(int dis[],int n) //To print the shortest path
{
int i;
cout<<"\nVertices\tMinimum distance";
for(i=0;i<n;i++)
{
cout<<"\n"<<i<<"\t"<<dis[i];
}
}
int main()
{
graph g;
int start;
g.readgraph();
cout<<"\nThe entered graph is::\n";
g.printgraph();
g.dij();
return 0;
}
It seems like the fault is in the loop for finding the shortest path in the dij() function. But still i am not able to figure out the problem. Please help me out... :-|
Upvotes: 0
Views: 370
Reputation: 29
Just a quick question: in min(...)
the n
is which n
? n
is graph::n
or n
from the parameter list?
Upvotes: 1
Reputation: 4738
Seems like you have many problem of initialization but with this change your said error would go.
In function int min(int dis[],bool vis[],int n)
initialize index
to zero
.
int index=0
Upvotes: 2