gpt4 book ai didi

c++ - Floyd-Warshall 算法的路径重建不适用于某些值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:07 26 4
gpt4 key购买 nike

我像那里一样实现算法 http://en.algoritmy.net/article/45708/Floyd-Warshall-algorithm .

 void Graph::floydWarshal()
{
for (int k = 0; k < weight_matrix.size(); k++)
{
for (int i = 0; i < weight_matrix.size(); i++)
{
for (int j = 0; j < weight_matrix.size(); j++)
{
if (weight_matrix[i][k] != infinity && weight_matrix[k][j] != infinity)
{
int temp = weight_matrix[i][k] + weight_matrix[k][j];
if (weight_matrix[i][j] > temp)
{
weight_matrix[i][j] = temp;
predecessors[i][j] = predecessors[k][j];
}
}
}
}
}
}

void Graph::getPath(int start, int finish, std::vector<int> &path)
{
if (start == finish)
{
path.push_back(start);
}
else if (predecessors[start][finish] == 0)
{
path.clear();
return;
}
else
{
getPath(start, this->predecessors[start][finish], path);
path.push_back(finish);
}
}

在构造函数中初始化前辈

for (int i = 0; i < weight_matrix.size(); i++)
{
for (int j = 0; j < weight_matrix[i].size(); j++)
{
if (weight_matrix[i][j] != 0 && weight_matrix[i][j] != infinity)
{
predecessors[i][j] = i;
}
else
{
predecessors[i][j] = -1;
}
}
}

这是长度矩阵

0   2 1  4   inf inf
2 0 7 3 inf inf
1 i 0 5 10 4
4 7 5 0 inf 5
inf 3 10 inf 0 4
inf inf 4 5 4 0

它仅适用于某些值,例如从顶点 5 到顶点 0 构建的路径(返回 5 2 0)。但从 0 到 5 不构建(返回 5)。长度矩阵正确构建

最佳答案

我认为问题出在这一行(寻找一条不可能的路径):

else if (predecessors[start][finish] == 0)

你的节点是从零开始索引的,所以前导可以合法地等于 0。当路由涉及节点零时,您将错误地清除路径。

试试用这个代替:

else if (predecessors[start][finish] == -1) 

关于c++ - Floyd-Warshall 算法的路径重建不适用于某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com