我正在解决以下Leetcode问题:
https://leetcode.com/problems/find-if-path-exists-in-graph/
我得到以下错误:
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
方法的代码:
class Solution {
public:
void dfs(int *visited,int node,vector<vector<int>>&adj)
{
visited[node]=1;
for(auto child:adj[node])
{
if(visited[child]==-1)
dfs(visited,child,adj);
}
}
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj;
for(auto it:edges)
{
adj[it[0]].push_back(it[1]);
}
int visited[n];
for(int i=0;i<n;i++)
visited[i]=-1;
dfs(visited,source,adj);
return visited[destination]==1;
}
};
我几乎在每个图形问题中都会得到这个错误。有人能指出这个错误吗?
adj的外向量
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj;
for(auto& it:edges)
{
if (adj.size() < (it[0] + 1))
{
adj.resize(it[0] + 1);
}
adj[it[0]].push_back(it[1]);
}
//Rest of the code
}