#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <queue>
#include <fstream>
std::ifstream fin("doc/bfs.in");
std::ofstream fout("doc/bfs.out");
const int NMAX = 100000;
std::vector<std::list<int>> L;
int vis[NMAX], d[NMAX];
void making_lists(int m) {
// Making the ajacengy list
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
L[x - 1].push_front(y);
}
}
void bfs(int x) {
std::queue<int> q; // The tail
q.push(x);
d[x] = 0; // The distance
vis[x] = 1; // The visited nodes
while (!q.empty()) {
x = q.front();
q.pop();
for(auto var : L[x - 1]) {
// Checking if the node hasn't been visited yet
if (!vis[var]) {
q.push(var); // Adding all the adjacent nodes to the tail
d[var] = d[x] + 1; // Saving the distance from the st node to each node form graph
vis[var] = 1; // Marking the node as "visited"
}
}
}
}
int main (int argc, char *argv[]) {
// Test if the file has succesfully open
if (!fin.is_open()) {
std::cout << "Error: Failed to open file." << std::endl;
exit(1);
}
int n, m, st;
// Reading graph data
fin >> n; // Number of nodes
fin >> m; // Number of vertices
fin >> st; // Starting nod
L.resize(n);
making_lists(m);
bfs(st);
// Marking all the inacesable nodes with -1
for (int i = 1; i < n + 1; i++) {
// With the exception of st
if (d[i] == 0 && i != st) {
d[i] = -1;
}
fout << d[i] << " ";
}
fin.close();
fout.close();
return 0;
}