Pagini recente » Cod sursa (job #1941085) | Cod sursa (job #1144768) | Cod sursa (job #610520) | Cod sursa (job #2574485) | Cod sursa (job #2764379)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
const int maxVert = 100001;
vector<int> Adj[maxVert];
queue<int> nodes;
int dist[maxVert];
int main() {
int n, m, s, x, y;
f >> n >> m >> s;
for (int i = 1; i <= m; ++i) {
f >> x >> y;
Adj[x].push_back(y);
}
nodes.push(s);
int front;
for (int i = 1; i <= n; ++i) {
dist[i] = -1;
}
dist[s] = 0;
while (!nodes.empty()) {
front = nodes.front();
nodes.pop();
int neighbours = Adj[front].size();
for (int i = 0; i < neighbours; ++i) {
if (dist[Adj[front][i]] == -1) {
dist[Adj[front][i]] = dist[front] + 1;
nodes.push(Adj[front][i]);
}
}
}
for (int i = 1; i <= n; ++i) {
g << dist[i] << " ";
}
f.close();
g.close();
return 0;
}