Pagini recente » Cod sursa (job #319286) | Cod sursa (job #738111) | Cod sursa (job #966680) | Cod sursa (job #367225) | Cod sursa (job #2681642)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
vector<int> bfs(int n, vector<vector<int>>& edges, int start = 1) {
vector<int> touch(n + 1, -1);
vector<int> visited(n + 1, 0);
queue<pair<int, int>> q;
pair<int, int> p;
q.push(make_pair(0, start));
touch[start] = 0;
visited[start] = 1;
while(!q.empty()) {
p = q.front();
q.pop();
for (auto elem: edges[p.second]) {
if (visited[elem] == 0) {
q.push(make_pair(p.first + 1, elem));
touch[elem] = p.first + 1;
visited[elem] = 1;
}
}
}
return touch;
}
int main()
{
ios_base::sync_with_stdio(false);
ifstream in("bfs.in");
ofstream out("bfs.out");
int n, m, x, y, s;
in >> n >> m >> s;
vector<vector<int>> edges(n + 1);
for(int i = 0; i < m; i++) {
in >> x >> y;
edges[x].push_back(y);
}
in.close();
vector<int> touch = bfs(n, edges, s);
for(int i = 1; i <= n; i++) {
out << touch[i] << " ";
}
out.close();
return 0;
}