Pagini recente » Cod sursa (job #2824527) | Cod sursa (job #1238298) | Cod sursa (job #2478168) | Cod sursa (job #2429887) | Cod sursa (job #2695641)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n,m,s;
void bfs(int s, vector<int> graf[], int rez[])
{
int v[n+1]={0};
queue<int> q;
v[s]=1;
q.push(s);
rez[s]=0;
while(q.empty()==false)
{
int x = q.front();
q.pop();
for(auto y : graf[x])
{
if(v[y]==0)
{
q.push(y);
v[y]=1;
rez[y]=rez[x]+1;
}
}
}
}
int main()
{
fin>>n>>m>>s;
vector<int> graf[n+1];
int rez[n+1];
for(int i=1;i<=n;i++)
rez[i]=-1;
while(m--)
{
int x,y;
fin>>x>>y;
graf[x].push_back(y);
}
bfs(s,graf,rez);
for(int i=1;i<=n;i++)
{
fout<<rez[i]<<" ";
}
return 0;
}