Pagini recente » Cod sursa (job #1083899) | Cod sursa (job #2119525) | Cod sursa (job #1829206) | Cod sursa (job #1493262) | Cod sursa (job #3246073)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> graph;
vector<int> dist;
vector<bool> visited;
queue<int> q;
int main(){
int n, m, s;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> n >> m >> s;
graph = vector<vector<int>>(n+1, vector<int>());
dist = vector<int>(n+1);
visited = vector<bool>(n+1);
for(int i = 1; i <= m; i++){
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
dist[s] = 0;
visited[s] = true;
q.push(s);
while(!q.empty()){
int aux = q.front();
for(int neighbour : graph[aux]){
if(!visited[neighbour]){
dist[neighbour] = dist[aux] + 1;
visited[neighbour] = true;
q.push(neighbour);
}
}
q.pop();
}
for(int i = 1; i <= n; i ++){
if(dist[i] == 0 && i != s){
fout << -1 << ' ';
}
else{
fout << dist[i] << ' ';
}
}
return 0;
}