Djikstra 最短路径算法的堆实现,C++

Heap implementation of Djikstra's Shortest-path algorithm, C++

本文关键字:实现 C++ 最短路径 算法 Djikstra      更新时间:2023-10-16

>编辑:下面的代码运行良好,问题出在我的堆实现中。如果您正在寻找 Djikstra 最短路径算法的基于堆的版本C++实现,请随意查看。

在过去的几个小时里,我一直在尝试调试 Djikstra 最短路径算法(使用堆的 O(m*log(n) 版本)的实现,但仍然在测试用例的一小部分中遇到错误。我遇到问题的测试用例相当大(图中有 200 个节点),所以我不知道将其包含在这里有多大用处。可以说,我的实现似乎为除几个节点之外的所有节点生成了正确的最短路径。

对于任何算法专家,请您看看我有什么,并告诉我哪里出错了?

#include "Heap.h"
#include <sstream>
#include <string>
#include <sstream>
#include <iostream>
void ReadFile(std::vector<Edge> adjList[], std::string fileName);
const int NUM_VERTICES = 200;
const int START_VERTEX = 29;
int main(){
    //valid entries in adjList start from[1] so that vertex #1 is stored in [1].
    std::vector<Edge> adjList[NUM_VERTICES + 1];
    std::vector<int> shortestPaths(NUM_VERTICES + 1);
    ReadFile(adjList, "dijkstraData.txt");
    //ReadFile(adjList, "test.txt");
    Heap heap(NUM_VERTICES);
    heap.InitializeForDjikstras(); 
    HeapEntry min(0, 0);
    //for each of the remaining vertices, process using Djikstra's greedy selection rule
    for (int i = 0; i < NUM_VERTICES; i++){
        shortestPaths[min.id] = min.key;
        //recalculate keys of any nodes that now have edges crossing the boundary between X(processed) and V-X(unprocessed)
        for (int q = 0; q < adjList[min.id].size(); q++){
            int headID = adjList[min.id][q].id;
            int costToHead = adjList[min.id][q].cost;
            HeapEntry head = heap.Delete(headID);
            if (head.key > shortestPaths[min.id] + costToHead) {
                head.key = shortestPaths[min.id] + costToHead;
            }
            heap.Insert(head);
        }
    }
    return 0;
}

如果看到我的堆实现或完整的 ReadFile 实现会有所帮助,请告诉我,我会发布它。我很确定它们工作正常。

问题实际上出在我的堆实现中。上面的代码是正确的,所以任何寻找 Djikstra 算法的堆实现的人都可以随意看看。