我正在C++中實現Shortest Path Problem。基本上用戶輸入SourceVertex
,函數FindShortestPath(int SourceVertex)
找到並打印從SourceVertex
到所有其餘頂點的最短路徑。最短路徑實現問題
void Graph::FindShortestPath(int SourceVertex)
{
cout<<"The shortest paths from "<<SourceVertex<<" are"<<endl;
//initialize the 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;}
我得到以下輸出
The shortest paths from 4 are
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
即印刷是正確的第一組。更新部分有問題。我似乎無法弄清楚。
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;
}
以下是我輸入代碼
請顯示不良行爲發生的數據。 – Codor