Pagini recente » Cod sursa (job #2409399) | Cod sursa (job #3137713) | Cod sursa (job #2943547) | Cod sursa (job #561192) | Cod sursa (job #2510686)
#include <iostream>
#include <queue>
#include <fstream>
#include <vector>
using namespace std;
bool viz[100001];
vector<int> la[100001];
int cost[100001];
queue<int> bf;
int main() {
int n, m;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
//citire
int st;
fin >> n >> m >> st;
int a, b;
for(int i = 1; i <= m; i++) {
fin >> a >> b;
la[a].push_back(b);
//la[b].push_back(a);
}
for(int i = 0; i <= n; i++) cost[i] = -1;
bf.push(st);
cost[st] = 0;
while(!bf.empty()) {
int x = bf.front();
int cst_x = cost[x];
bf.pop();
//cout << x << " ";
viz[x] = true;
for(int i = 0; i < la[x].size(); i++) {
if(!viz[la[x][i]]) {
bf.push(la[x][i]);
cost[la[x][i]] = cst_x + 1;
}
}
}
//cout << endl;
for(int i = 1; i <= n; i++) {
fout << cost[i] << " ";
}
fin.close();
fout.close();
return 0;
}