Pagini recente » Cod sursa (job #3304994) | Cod sursa (job #196735) | Cod sursa (job #3331863) | Borderou de evaluare (job #1514460) | Cod sursa (job #3338138)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace std;
vector <int> graph[100005];
int n, x, y, nr, i, m, s, dist[100005], auxi;
queue <int> q;
void bfs ( int node ) {
q.push ( node );
dist[node] = 0;
while ( !q.empty() ) {
auxi = q.front();
q.pop();
for ( auto j: graph[auxi] ) {
if ( dist[j] > dist[auxi]+1 ) {
dist[j] = dist[auxi]+1;
q.push ( j );
}
}
}
}
int main()
{
ifstream cin ("bfs.in");
ofstream cout ("bfs.out");
cin >> n >> m >> s;
for ( i = 1; i <= m; i++ ) {
cin >> x >> y;
graph[x].push_back(y);
}
for ( i = 1; i <= n; i++ ) {
dist[i] = n+1;
}
bfs ( s );
for ( i = 1; i <= n; i++ ) {
if ( dist[i] == n+1 ) {
dist[i] = -1;
}
cout << dist[i] << ' ';
}
return 0;
}