I am solving the following Leetcode problem:
https://leetcode.com/problems/find-if-path-exists-in-graph/
I am getting the following error:
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
The code for my approach:
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;
}
};
I'm getting this error for almost every graph problem. Can someone point out the mistake?
CodePudding user response:
The outer vector of adj should be resized, before adding elements to the inner vector.
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj;
for(auto& it:edges)
{
adj.resize(it[0] 1);
adj[it[0]].push_back(it[1]);
}
//Rest of the code
}