簡體   English   中英

使用 BFS 算法時出現運行時錯誤

[英]Got runtime error while using BFS algorithm

m 個航班連接了 n 個城市。 每個航班從城市 u 出發,以價格 w 到達 v。

現在給定所有城市和航班,連同起始城市 src 和目的地 dst,您的任務是找到從 src 到 dst 最多 k 個站點的最便宜的價格。 如果沒有這樣的路由,output -1。

前任:

示例 1:

輸入:

n = 3, 

edges = [[0,1,100],[1,2,100],[0,2,500]]


src = 0, dst = 2, k = 1

Output: 200 解釋: 圖表如下所示:

在此處輸入圖像描述

這是我的代碼:

class Solution {
public:
    int ans=INT_MAX;
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
        vector<vector<vector<int>>>g;
        for(auto f:flights)
        {
            int from=f[0];
            int to=f[1];
            int cost=f[2];
            g[from].push_back({to,cost});
        }
        queue<vector<int>>q;
        q.push({src,0,-1});
        while(!q.empty())
        {
             vector<int>curr=q.front();
            q.pop();
            int currCity=curr[0];
            int currCost=curr[1];
            int currK=curr[2];
            
            if(currCity == dst)
            {
                ans=min(currCost,ans);
                continue;
            }
            for(auto x:g[currCity])
            {
                if(currK+1<=K && currCost+x[1]<ans)
                {
                    q.push({x[0],currCost+x[1],currK+1});
                }
            }
            
        }
        if(ans == INT_MAX)
        {
            return -1;
        }
        return ans;
    }
};

我曾經使用過 BFS 算法。

但是我收到以下錯誤:

第 924 行:字符 9:運行時錯誤:引用綁定到 null 類型指針 'std::vector<std::vector<int, std::allocator >, std::allocator<std::vector<int, std::分配器 > > >' (stl_vector.h) 摘要:UndefinedBehaviorSanitizer:未定義行為 /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include /c++/8/bits/stl_vector.h:933:9

我無法找出我哪里出錯了。

謝謝。

查看這段代碼:

        vector<vector<vector<int>>>g;
        for(auto f:flights)
        {
            int from=f[0];
            int to=f[1];
            int cost=f[2];
            g[from].push_back({to,cost});
        }

最初g是一個空向量。 您使用它做的第一件事是訪問不存在的元素: g[from]

你的意思可能是:

vector<vector<vector<int>>>g(n);

在這里,您創建了一個 3D 向量,其中第一個維度已正確初始化。

其他注意事項:在不需要的地方使用向量。 您在不檢查實際大小的情況下使用已知固定數量的元素這一事實意味着該向量被濫用:

            int from=f[0];
            int to=f[1];
            int cost=f[2];

嘗試通過使用結構體、元組等來避免這種情況。結構體更合適,因為您甚至知道每個元素的作用: fromtocost

這段代碼效率很低:

for(auto x:g[currCity])
    ...

只要g是 3D 向量, auto x就成為每個 2D 元素的完整副本。 試試看: for(const auto &x:g[currCity])

vector<vector<vector<int>>>g; should be `vector<vector<vector<int>>>g(n);` 

其中 n 可以是任意數字。 因為您試圖獲取特定的索引。 你必須初始化你的向量。

暫無
暫無

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

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