#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
void afis(int**v,int n)
{
for(int i=0; i<=n; i++)
{
for(int j=0; j<=n; j++)
cout<<v[i][j]<<' ';
cout<<'\n';
}
}
void lAdiacentaV2(int **v,int m,int n)
{
int *vecini=(int*)malloc((n+1)*sizeof(int));
for(int i=1;i<=n;i++)
vecini[i]=1;
for(int i=0;i<m;i++)
{
int x,y;
fin>>x>>y;
v[x][vecini[x]++]=y;
}
/* for(int i=1;i<=n;i++)
{
for(int j=1;j<vecini[i];j++)
cout<<v[i][j]<<' ';
cout<<'\n';
}*/
free(vecini);
}
void lAdiacenta(int **v,int m)
{
for(int i=0; i<m; i++)
{
int x,y;
fin>>x>>y;
v[x][y]=1;
}
}
struct vf
{
int colour;//-1 = negru, 0 = gri, 1=alb
int d;//distanta
int pre;
};
void bfs(int **v,int s,int n)
{
struct vf* varfuri=(struct vf*)malloc((n+1)*sizeof(struct vf));
int inf=1000000;
for(int i=1; i<=n; i++)
{
varfuri[i].colour=1;
varfuri[i].d=inf;
varfuri[i].pre=0;
}
varfuri[s].colour=0;
varfuri[s].d=0;
varfuri[s].pre=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
int i=1;
while(v[u][i]!=0)
{
if(varfuri[v[u][i]].colour==1)
{
varfuri[v[u][i]].colour=0;
varfuri[v[u][i]].d=varfuri[u].d+1;
varfuri[v[u][i]].pre=u;
q.push(v[u][i]);
}
i++;
}
varfuri[u].colour=-1;
}
for(int i=1; i<=n; i++)
if(varfuri[i].d==inf)
fout<<-1<<' ';
else
fout<<varfuri[i].d<<' ';
free(varfuri);
}
int** aloca(int** v,int n)
{
v=(int**)malloc((n+1)*sizeof(int*));
for(int i=0; i<=n; i++)
v[i]=(int*)calloc((n+1),sizeof(int));
return v;
}
void dealoca(int **v,int n)
{
for(int i=0; i<n; i++)
free(v[i]);
free(v);
}
int main()
{
int **v;
int n,m,s;
fin>>n>>m>>s;
v=aloca(v,n);
lAdiacentaV2(v,m,n);
//afis(v,n);
bfs(v,s,n);
dealoca(v,n);
return 0;
}