加权图的开始和结束的最短路径

Shortest path given beginning and end of a weighted graph

本文关键字:最短路径 结束 开始 加权图      更新时间:2023-10-16

我必须在文件中读取才能创建加权图。必须使用文件输入找到最短路径。文件将作为第一行=数字和下方的每一行构造,其中3个数字给出:0 1 2,其中0是边缘的开始,1是边的末端,而2是重量。我尝试在创建图形时尝试实现邻接矩阵,但没有运气。任何建议都将不胜感激。

尝试重组我在文件中阅读的方式,并尝试调整FindshortEstpath功能。

void createGraph(string file_name) //Function to create a graph based on a file, whose name is file_name.
{
    ifstream f(file_name);
    if (f.fail())
    {
        return;
    }
    string line;
    getline(f, line);
    int num = stoi(line);
    numVertices = num;
    int data[50][50];
    string line2;
    int num1 = 0, num2 = 0, num3 = 0;
    while (!f.eof())
    {
        f >> num1;
        f >> num2;
        f >> line2;
        num3 = stoi(line2);
        data[num1][num2] = num3;
    }
}
//////////////////shortest path function
string findShortestPath(int start, int end)
{
    int data[numVertices][numVertices];
    int dist[numVertices];
    bool sptSet[numVertices];
    int parent[numVertices];
    for (int i = 0; i < numVertices; i++)
    {
        parent[0] = -1;
        dist[i] = INT_MAX;
        sptSet[i] = false;
    }
    dist[start] = 0;
    for (int count = 0; count < numVertices - 1; count++)
    {
        int u = minDistance(dist, sptSet);
        sptSet[u] = true;
        if (sptSet[u] == end)
            break;
        for (int v = 0; v < numVertices; v++)
            if (!sptSet[v] && data[u][v] && dist[u] + data[u][v] < dist[v])
            {
                parent[numVertices] = end;
                dist[v] = dist[u] + data[u][v];
            }
    }
    printSolution(parent);

输出不是输出最短路径,并且正在打印随机数。

在您的findShortestPath功能data[numVertices][numVertices]中与createGraph函数中的data变量不同。

查看此https://www.geeksforgeeks.orgs.org/scope-of-variables-in-in-c/或尝试在变量范围上查找其他来源。

在您的函数findShortestPath中,您已声明了一个名为data的本地数组,该数组应该存储邻接矩阵数据。但是,您从未写过任何数据!考虑将矩阵作为函数参数传递。您的功能签名应该看起来像这样:

findShortestPath(int** data, int numVertices, int start, int end)

另外,避免使用VLA,因为它不是标准的一部分。考虑使用new在堆上创建二维数组。(并且完成完成后不要忘记做delete[]!(

,也可以使用std::vector<std::vector<int>>,如果您不想手动管理数组的寿命。