最短路径实施问题
Shortest Path Implementation Issue
我正在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()函数会有所帮助。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- libssh 问题编译问题未定义的错误
- C 代码问题?编译器问题?代码块
- 我对这个问题有问题,我的输出不正确
- 面临功能问题的问题
- 递归中的异常问题(8皇后问题)
- 指针问题?这个问题?类问题
- VS 2010构建问题:参考问题
- 问题4-Q过程问题
- c++这个问题的问题在哪里?(带参数的构造函数)