The question is to calculate the length of the shortest path to each vertex starting from 0 to all other vertices and store them inside a array and then print that array. I have written the following code but the code is giving me SIGSEGV in all of the online compliers
#include<bits/stdc++.h>
using namespace std;
class Graph
{
private :
int v;
vector<int>*adj;
public:
Graph(int v){
this->v = v;
adj = new vector<int>[v];
}
void insert(int x,int y)
{
adj[x].push_back(y);
adj[y].push_back(x);
}
void print()
{
for(int i=0;i<v;i++)
{
for(int j=0;j<adj[i].size();j++)
cout<<adj[i][j]<<" ";
cout<<endl;
}
}
void shortestPath(int source)
{
cout<<"v here is "<<v<<endl;
bool visited[v];
int dist[v];
for(int i=0;i,v;i++)
visited[i] = false;
for(int i=0;i<v;i++)
dist[i] = INT_MAX;
queue<int>q;
q.push(0);
visited[0] = true;
dist[0] = 0;
while(!q.empty())
{
cout<<"i am here"<<endl;
int j = q.front();
q.pop();
for(int i : adj[j])
{
if(!visited[i])
{
visited[i] = true;
dist[i] = dist[j]+1;
q.push(i);
}
}
}
cout<<"the output array for the shortest path is"<<endl;
for(int i=0;i<v;i++)
cout<<dist[i]<<" ";
}
};
int main()
{
Graph g(4);
g.insert(0,1);
g.insert(1,2);
g.insert(2,3);
g.insert(0,2);
g.insert(1,3);
g.shortestPath(0);
}
please help me identify my mistake my code basically has an adjacency list for my graph thanks a lot in advance.