Pagini recente » Cod sursa (job #165047) | Cod sursa (job #3137730) | Infoarena Monthly 2012 - Runda 5 - Solutii | Cod sursa (job #790048) | Cod sursa (job #2756079)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
int bfs(int n, vector<int> adj[], int st, int end) {
bool vis[n]{};
queue<pair<int, int>> Q;
Q.push({st, 0});
vis[st] = 1;
while(!Q.empty()) {
int currNode = Q.front().first, currDist = Q.front().second;
Q.pop();
if(currNode == end) {
return currDist;
}
for(int nxt : adj[currNode]) {
if(!vis[nxt]) {
Q.push({nxt, currDist + 1});
vis[nxt] = 1;
}
}
}
return -1;
}
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
fin >> n >> m >> s;
vector<int> adj[n];
while(m--) {
int x, y;
fin >> x >> y;
adj[x - 1].push_back(y - 1);
}
for(int i = 0; i < n; i++) {
fout << bfs(n, adj, s - 1, i) << ' ';
}
fin.close();
fout.close();
return 0;
}