c++ - Shortest Path Implementation Issue -
i implementing shortest path problem in c++. user enters sourcevertex , function findshortestpath(int sourcevertex) finds , prints shortest paths sourcevertex remaining vertices.
void graph::findshortestpath(int sourcevertex) { cout<<"the shortest paths "<<sourcevertex<<" are"<<endl; //initialize shortestpatharray for(int a=0;a<numberofvertices;a++) shortestpatharray[a]=numeric_limits<int>::max(); shortestpatharray[sourcevertex]=0; for(int a=0;a<numberofvertices;a++) { if(weightmatrix[sourcevertex][a]!=0) shortestpatharray[a]=weightmatrix[sourcevertex][a]; } cout<<"direct edges length"<<endl; for(int a=0;a<numberofvertices;a++) { cout<<sourcevertex<<"->"<<a<<"="<<shortestpatharray[a]<<endl; } cout<<"shortest path after updating"<<endl; for(int a=0;a<numberofvertices;a++) for(int b=0;b<numberofvertices;b++) if(weightmatrix[a][b]!=0)//edge exists { if(shortestpatharray[b]>(shortestpatharray[a]+weightmatrix[a][b])) { shortestpatharray[b]= shortestpatharray[a]+weightmatrix[a][b];}} for(int a=0;a<numberofvertices;a++) cout<<sourcevertex<<"->"<<a<<"="<<shortestpatharray[a]<<endl;} i following output
the shortest paths 4 direct edges length 4->0=2147483647 4->1=6 4->2=10 4->3=4 4->4=0 shortest path after updating 4->0=2147483647 4->1=-2147483645 4->2=-2147483646 4->3=-2147483644 4->4=-2147483647 the first set printed correct. in wrong in updating part. can't seem figure out.
edit-1
int main(){ graph g(5); g.addedge(0,4,2); g.addedge(0,2,3); g.addedge(0,1,5); g.addedge(1,3,6); g.addedge(1,2,2); g.addedge(4,3,4); g.addedge(4,1,6); g.addedge(4,2,10); g.addedge(2,1,1); g.addedge(2,3,2); g.findshortestpath(4); return 0; } following input code
if(weightmatrix[a][b]!=0)//edge exists { if(shortestpatharray[b]>(shortestpatharray[a]+weightmatrix[a][b])) { shortestpatharray[b]= shortestpatharray[a]+weightmatrix[a][b]; } } here e.g a=0 value of shortestpatharray[a]=2147483647; i.e max range, , in value adding more value going out of range. try smaller value max limit.
Comments
Post a Comment