There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.
Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.
Ex:
Example 1:
Input:
n = 3,
edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200 Explanation: The graph looks like this:
Here is my code:
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;
}
};
I had use the BFS algorithm.
However I got the following error:
Line 924: Char 9: runtime error: reference binding to null pointer of type 'std::vector<std::vector<int, std::allocator >, std::allocator<std::vector<int, std::allocator > > >' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:9
I am not able to find out where I went wrong.
Thanks.