Dijkstra算法条件不正确
dijkstra algorithm incorrect conditional
我正在使用优先队列处理Dijkstra算法。我一直在进行很多研究,我认为我的代码正在遵循该算法,但是在比较最短路径
时,我无法进入条件。 void dijkstra( int startingID ) {
priority_queue<Vertex*, vector<Vertex*>, PathWeightComparer> dijkstra_queue{};
vector<Vertex*> vert;
vert = _vertices;
int n = vert.size();
vector< double > dis(n);
for (int i = 0; i < n; i++)
{
dis[i] = std::numeric_limits< double >::infinity();
}
vert[startingID]->setPathWeight(startingID);
dis[startingID] = 0;
Vertex* temp = vert[startingID];
dijkstra_queue.push(temp);
while (!dijkstra_queue.empty())
{
double dist = dijkstra_queue.top()->getPathWeight();
double u = dijkstra_queue.top()->getId();
dijkstra_queue.pop();
for (auto i : vert)
{
double v = i->getId();
double weight = i->getPathWeight();
double distance_total = dist + weight;
cout << "distance_total " << distance_total << " dis[v] " << dis[v] << endl;
if (distance_total < dis[v]) //PROBLEM
{
dis[v] = distance_total;
Vertex* temp2 = i;
temp2->setPathWeight(dis[v]);
dijkstra_queue.push(temp2);
}
}
}
}
};
这是Graph类
class Graph
{
vector<Vertex*> _vertices; // All vertices in the graph (vertex id == index)
int _last_startingID = -1;
这是顶点类
class Vertex
{
private:
int _id; // ID (key) of given vertice
bool _known = false; // Dijkstra's algorithm "known" flag
Vertex* _path = nullptr; // Dijkstra's algorithm parent vertex pointer
// Weight of path through graph - starts at a true infinity (inf)
double _path_weight = std::numeric_limits<double>::infinity();
我尝试仅包含仅对Dijkstra函数重新保留的代码,但是如果有什么尚不清楚,我可以添加更多。
您对算法的实现不正确。
从队列中 pop()
pertex u
(因为它距源是最低的距离),您只能检查可直接从 u
到达的顶点(即从 u
到该顶点的边缘)。
您当前的实现似乎正在遍历所有顶点,无论它们是否可以直接从u
到达,也许因此,您对毫无意义的距离计算做了一些奇怪的事情。更具体地说,您的实施中的distance_total
似乎是毫无意义的。
Dijkstra算法背后的关键思想是:
dis[u] = must be shortest path from source to u since u was popped.
dis[v] = current_known_distance_to_v
Then, for all v where edge exists from u to v:
IF dis[u] + weight(u, v) < dis[v]:
// going via u is better than the current best known distance to v
dis[v] = dis[u] + weight(u, v)
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- Dijkstra算法条件不正确
- 条件表达式行为不正确
- if-else 语句中的条件计算不正确