I am trying to solve the problem using the adjacency list now. But the problem I am facing here is when I am trying to insert the element in an adjacency list, it stores the value in the sequence I have entered. For example for the test case:
5 8 0 1 0 4 1 2 2 0 2 4 3 0 3 2 4 3
My output is:
0 1 4 2 3
Expected output is:
0 1 2 3 4.
It is because my adjacency list stores the value in the fashion it was not entered in a sorted manner. How would I store it in a sorted manner? If I sort it, it just increases the complexity of the code. Please help.
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void addEdge(vector<ll> edges[], ll u, ll v)
{
edges[u].push_back(v);
edges[v].push_back(u);
}
void BFS(vector<ll> edges[], ll v, bool * visited, queue<ll> q)
{
while(!q.empty())
{
ll s = q.front();
cout << s << " ";
q.pop();
for(ll i = 0; i < edges[s].size(); i++)
{
if(!visited[edges[s][i]])
{
visited[edges[s][i]] = true;
q.push(edges[s][i]);
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll v, e;
cin >> v >> e;
vector<ll> edges[v];
for(ll i = 0 ; i < e; i++)
{
int x, y;
cin >> x >> y;
addEdge(edges, x, y);
}
bool * visited = new bool[v];
memset(visited, false, sizeof(visited));
queue<ll> q;
q.push(0);
visited[0] = true;
BFS(edges, v, visited, q);
return 0;
}