#include <bits/stdc++.h>
using namespace std;
typedef long long int ll ;
int main() {
int n ;
cout<<"Number of nodes (vertices) in the graph: ";
cin>> n ;
int m ;
cout<<"Number of edges in the graph: ";
cin>> m ;
//array of vectors to store adjacency list
vector <int> G[n+5] ;
int i = 1 ;
while(i<=m){
int x,y;
cout<<"Take the graph node and edges as input: "<<endl;
cin>>x>>y;
//Graph is undirected
G[x].push_back(y);
G[y].push_back(x);
i++;
}
//declaring a queue
queue<int>q;
int source;//main node
cout<<"Source: ";
cin>>source;
q.push(source);//pushing the source node in the queue
int visited[n+5]={0};//declaring an empty array 0 means its not visited
visited[source]=1;//source node has been visited hence set it to = 1
int level[n+5]={0};//declaring leveel array that tells us the level of each node
level[source]=0;//lvl of source node which we mean the source node is 0 as we start from here
while(!q.empty())
{
//BFS ALGO
int v=q.front();// Get the front element of the queue
q.pop(); // Remove the front element
for(auto u: G[v])
{
//this simply means you'r iterating through all nodes connected to node y
if(visited[u]==0)// If node 'x' is not visited
{
q.push(u);// Push 'x' into queue
visited[u]=1;// Mark as visited
level[u]=level[v]+1;// Distance of 'x' = distance of 'y' + 1
}
}
}
i = 1 ;
while(i<=n){
cout<<level[i]<<" ";//lvl[i] gives the shortest distance of each node from source.
i++;
}
return 0 ;
}