Pagini recente » Cod sursa (job #3310439) | Cod sursa (job #3305292)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
const int Nmax=1e5+5;
int n, m, s;
vector<int> ad[Nmax];
int dist[Nmax];
queue<int> q;
void bfs(int org){
for (int i=1; i<=n; i++)
dist[i]=-1;
dist[org]=0;
q.push(org);
while (!q.empty()){
int node=q.front();
q.pop();
for (auto it:ad[node])
if (dist[it]==-1){
dist[it]=dist[node]+1;
q.push(it);
}
}
}
int main(){
fin>>n>>m>>s;
for (int i=0; i<m; i++){
int a, b;
fin>>a>>b;
ad[a].push_back(b);
}
bfs(s);
for (int i=1; i<=n; i++)
fout<<dist[i]<<' ';
return 0;
}