I'm trying to implement a program which performs a DFS Traversal. The program works fine when N is predefined to a specific value and the edges are also given actual values (please refer to the commented section of the code). The problem arises when I try to get the value of N from the user, and when I try to accept the edges from the user. I've debugged and it crashes at line adj[u].push_back(v);
. However, if I write adj[0].push_back(1)
i.e. actual numbers instead of variables it works fine, but it crashes when I accept u & v from the user.
#include <iostream>
#include <stack>
#include <list>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
int N, M;
vector<std::list<int> > adj (N);
vector<bool> visited (N);
void dfs( int start);
int main()
{
cin>>N>>M;
for(int i = 0; i < M; i++ )
{
int u,v;
cin>>u;
cin>>v;
u--;
v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
/* adj[0].push_back(1);
// adj[1].push_back(2);
// adj[1].push_back(0);
// adj[1].push_back(1);
// adj[2].push_back(0);
//adj[2].push_back(1);
// */
std::vector<std::list<int> >::iterator i;
int c=0;
for(std::vector<std::list<int> >::iterator i= adj.begin(); i!=adj.end(); i++)
{
cout<<"Vertices connected to node "<<c<<"are ";
std::list<int> li=*i;
for(std::list<int>::iterator iter = li.begin(); iter!=li.end(); iter++)
{
cout<<*iter<<" ";
}
cout<<endl;
c++;
}
cout<<endl;
cout<<"DFS TRAVERSAL"<<endl;
dfs(0);
cout<<endl;
return 0;
}
void dfs( int start)
{
stack<int> s;
s.push(start);
while(!s.empty())
{
int top=s.top();
s.pop();
if(visited[top]==false)
{
cout<<" "<<top;
visited[top]=true;
std::list<int> li=adj[top];
for(std::list<int>::iterator iter= li.begin(); iter!=li.end(); iter++)
s.push(*iter);
}
}
}