BFS (Breadth-First Search) | Graph Theory C++ implementation
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
vector<ll> v[10000];
ll vis[10000];
ll dis[10000];
void BFS(ll node)
{
queue<ll> q;
q.push(node);
dis[node]=0;
vis[node]=1;
while(!q.empty())
{
ll cur;
cur=q.front();
q.pop();
for(ll i=0;i<v[cur].size();i++)
{
ll child;
child=v[cur][i];
if(vis[child]==0)
{
q.push(child);
dis[child]=dis[cur]+1;
vis[child]=1;
}
}
}
}
int main()
{
ll node,edge;
cin>>node>>edge;
while(edge--)
{
ll x,y;
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}
BFS(1);
for(ll i=1;i<=node;i++)
{
cout<<dis[i]<<endl;
}
return 0;
}
0 Comments