Pagini recente » Cod sursa (job #3338776) | Cod sursa (job #3342805) | Cod sursa (job #3341117) | Cod sursa (job #663940) | Cod sursa (job #3338988)
#include <bits/stdc++.h>
#define MAXN 100000
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector <int> graf[MAXN + 1];
int distanta[MAXN + 1];
int main()
{
int n, m, s, i, x, y, cur;
fin >> n >> m >> s;
for(i = 1; i <= m; i++){
fin >> x >> y;
graf[x].push_back(y);
}
for(i = 1; i <= n; i++){
distanta[i] = n + 1;
}
queue <int> q;
q.push(s);
distanta[s] = 0;
while(!q.empty()){
cur = q.front();
q.pop();
for(i = 0; i < graf[cur].size(); i++){
if(distanta[cur] + 1 < distanta[graf[cur][i]]){
distanta[graf[cur][i]] = distanta[cur] + 1;
q.push(graf[cur][i]);
}
}
}
for(i = 1; i <= n; i++){
if(distanta[i] == n + 1){
fout << "-1 ";
}else{
fout << distanta[i] << " ";
}
}
fout << "\n";
return 0;
}