BFS graph using c++ implementation
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
vector<ll>adj[100000];
ll dis[100000],vis[100000];
void bfs(ll node)
{
queue<ll>q;
q.push(node);
vis[node]=1;
while(!q.empty())
{
ll cur;
cur=q.front();
q.pop();
for(ll i=0;i<adj[cur].size();i++)
{
ll child=adj[cur][i];
if(vis[child]==0)
{
vis[child]=1;
dis[child]=dis[cur]+1;
q.push(child);
}
}
}
}
int main()
{
ll node,edge;
cin>>node>>edge;
while(edge--)
{
ll x,y;
cin>>x>>y;
adj[x].push_back(y);
adj[y].push_back(x);
}
bfs(1);
for(ll i=1;i<=node;i++)
{
cout<<dis[i]<<" ";
}
return 0;
}
0 Comments