Pagini recente » Cod sursa (job #1108495) | Cod sursa (job #1136497) | Cod sursa (job #1227158) | Cod sursa (job #1086680) | Cod sursa (job #3296967)
#include <fstream>
#include <vector>
#include <queue>
#define MAX_NODES 100000
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<int> g[MAX_NODES + 1];
int dist[MAX_NODES + 1];
int n, m, S;
void BFS(int source) {
int currNode;
queue<int> q;
for (int i = 0; i <= n; ++i) {
dist[i] = -1;
}
dist[source] = 0;
q.push(source);
while (!q.empty()) {
currNode = q.front();
q.pop();
for (auto neighbour : g[currNode]) {
if (dist[neighbour] == -1) {
dist[neighbour] = 1 + dist[currNode];
q.push(neighbour);
}
}
}
}
void readGraph() {
fin >> n >> m >> S;
int x, y;
for (int i = 0; i < m; ++i) {
fin >> x >> y;
g[x].push_back(y);
}
fin.close();
}
void printSolution() {
for (int i = 1; i <= n; ++i) {
fout << dist[i] << " ";
}
fout << "\n";
fout.close();
}
int main() {
readGraph();
BFS(S);
printSolution();
return 0;
}