Pagini recente » Cod sursa (job #3342579) | Cod sursa (job #3354568) | Cod sursa (job #1004262) | Cod sursa (job #3347489) | Cod sursa (job #3333538)
#include <fstream>
#include <vector>
#include <queue>
std::ifstream input ("bfs.in");
std::ofstream output ("bfs.out");
int main () {
int n, m ,s;
input >> n >> m >> s;
std::vector<std::vector<int>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int x, y;
input >> x >> y;
graph[x].push_back(y);
}
std::vector<int> distance(n + 1, -1);
std::queue<int> q;
distance[s] = 0;
q.push(s);
while (!q.empty()) {
int currentNode = q.front();
q.pop();
for (int neighborNode : graph[currentNode]) {
if (distance[neighborNode] == -1) {
distance[neighborNode] = distance[currentNode] + 1;
q.push(neighborNode);
}
}
}
for (int i = 1; i <= n; ++i) {
output << distance[i] << " ";
}
return 0;
}