Dijkstra算法找到两个顶点之间的最短距离 c++

Dijkstra's Algorithm finding the shortest distance between two vertices c++

本文关键字:之间 顶点 c++ 短距离 两个 算法 Dijkstra      更新时间:2023-10-16

我一直在研究一个程序,以获取有关途径如何工作的基础知识,并决定使用Dijkstra的算法来找到2D数组的两个点之间的最短距离用户选择。我已经使用了带有三种方法的图类类,一种用于阅读,打印和最短。但是,我不知道该如何为我制作的程序制作算法。任何帮助将不胜感激!

程序在这些值中读取,第一个值将第一个设置为称为size的变量,其余的将输入到2D数组中,称为距离。

4
0     1.7   0.3   0 
1.7   0     0.1   3.6 
0.3   0.1   0     0 
0     3.6   0     0

这是我的图形:

class Graph
{
 public:
  void read(const char* filename);
  void print(ostream& out);
  float shortest(int v1, int v2);
 private:
  int size;
  float max_edge_length;
  float distance[MAX_VERTICES][MAX_VERTICES];
};

下面是我创建读取方法的开始。

void Graph::read(const char* filename){
    int x, y;
    ifstream myfile(filename);
    if (myfile.good()){
        myfile >> size;
        for (y = 0; y < size; y++){
            for (x = 0; x < size; x++){
                myfile >> distance[x][y];
            }
        }
    }
} 
void Graph::print(ostream& out){
    out << size << endl;
    for (int y = 0; y < size; y++){
        for (int x = 0; x < size; x++){
            out << distance[x][y] << " ";
        }   
        out << endl;
    }
}
float Graph::shortest(int v1, int v2){

}

如果您的图形在读取后的读取后确定,并且通常使用最短。

您可以使用弗洛伊德的算法。比Dijkstra简单

取O(n^3)(n是您的图点号)构建一次,每次使用o(1)

最短查询

https://en.wikipedia.org/wiki/floyd–Warshall_algorithm

但是,如果您的图表的点号较大(例如100000)。2D阵列在商店图方面不好。它将花费100000*100000*sizeof(float)内存

您的罐头图表