最短路径实施问题

Shortest Path Implementation Issue

本文关键字:问题 施问题 最短路径      更新时间:2023-10-16

我正在C++中实现最短路径问题。基本上,用户输入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

打印的第一套是正确的。更新部分出现错误。我好像想不通。

编辑-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;
}

以下是我的输入代码

if(WeightMatrix[a][b]!=0)//edge exists
{   
    if(ShortestPathArray[b]>(ShortestPathArray[a]+WeightMatrix[a][b]))
    {
        ShortestPathArray[b]= ShortestPathArray[a]+WeightMatrix[a][b];
    }
}

例如,对于最短路径阵列[a]的a=0的值=2147483647;即最大范围,在这个值中,你添加了更多的值,所以它超出了范围。尝试使用比最大限制更小的值。

这为我解决了问题。

更改

if(WeightMatrix[a][b]!=0)//edge exists
            {   if(ShortestPathArray[b]>(ShortestPathArray[a]+WeightMatrix[a][b]))
            {
                ShortestPathArray[b]= ShortestPathArray[a]+WeightMatrix[a][b];}} 

if(WeightMatrix[a][b]!=0)//edge exists
            {   if(ShortestPathArray[b]>abs(ShortestPathArray[a]+WeightMatrix[a][b]))
            {
                ShortestPathArray[b]= ShortestPathArray[a]+WeightMatrix[a][b];}} 

添加abs解决了问题。CCD_ 4的某些值明显为负值。如果最初的某个值是numeric_limits<int>::max(),而我正在向它添加一些东西,那么最终的结果是负值。因此,添加abs()函数会有所帮助。