簡體   English   中英

給定加權圖開始和結束的最短路徑

[英]Shortest path given beginning and end of a weighted graph

我必須讀入一個文件來創建一個加權圖。 必須使用文件中的輸入找到最短路徑。 文件將被構造為第一行 = numVertices 並且下面的每一行都有 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]是不一樣的data在可變createGraph功能。

查看此https://www.geeksforgeeks.org/scope-of-variables-in-c/或嘗試查找有關變量范圍的其他來源。

在您的函數findShortestPath您已經聲明了一個名為data的本地數組,它應該存儲鄰接矩陣數據。 但是,您從未將任何數據寫入其中! 考慮將矩陣作為函數參數傳遞。 您的函數簽名應如下所示:

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

此外,避免使用 VLA,因為它不是標准的一部分。 考慮使用new在堆上創建一個二維數組。 (並且不要忘記在完成后執行delete[] !)

或者,如果您不想手動管理數組的生命周期,則可以使用std::vector<std::vector<int>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM