Pagini recente » Cod sursa (job #2654843) | Cod sursa (job #1226901) | Cod sursa (job #354698) | Cod sursa (job #1025954) | Cod sursa (job #1297062)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream go("bfs.out");
int n,m,x,y,s;
vector <vector < int > > g;
vector <int> dist;
vector <bool> used;
queue<int> q;
void bfs(int x){
dist[x]=0;
used[x]=true;
q.push(x);
while(!q.empty()){
x=q.front();
q.pop();
for(int i=0; i<g[x].size(); i++){
y=g[x][i];
if (!used[y]){
q.push(y);
used[y]=true;
dist[y]=dist[x]+1;
}
}
}
}
int main()
{
f>>n>>m>>s;
g.resize(n+1);
for(int i=0; i<=n; i++){
used.push_back(false);
dist.push_back(-1);
}
for(int i=0; i<m; i++){
f>>x>>y;
g[x].push_back(y);
}
bfs(s);
for(int i=1; i<=n; i++)
go<<dist[i]<<" ";
return 0;
}