Pagini recente » Cod sursa (job #2738336) | Istoria paginii preoni-2006/runda-1/solutii | Cod sursa (job #3168736) | Cod sursa (job #3289044) | Cod sursa (job #3275050)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int oo = 2e9;
int n, m, s;
vector <vector<int>> v;
queue <int> q;
vector <int> d;
void init() {
v = vector<vector<int>>(n + 1);
d = vector <int> (n + 1, oo);
}
void read() {
fin >> n >> m >> s;
init();
for(int i = 1; i <= m; ++i) {
int x, y;
fin >> x >> y;
v[x].push_back(y);
}
}
void bfs(int node) {
q.push(node);
d[node] = 0;
while(!q.empty()) {
int currentNode = q.front();
q.pop();
for(const auto& neighbour : v[currentNode]) {
if(d[currentNode] + 1 < d[neighbour]) {
d[neighbour] = d[currentNode] + 1;
q.push(neighbour);
}
}
}
}
int main() {
read();
bfs(s);
for(int i = 1; i <= n; ++i)
fout << (d[i] != oo ? d[i] : -1) << " ";
}