Pagini recente » Cod sursa (job #3367370) | Cod sursa (job #3367173) | Cod sursa (job #3364739) | Cod sursa (job #3367057) | Cod sursa (job #3367098)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int bfs(vector<vector<int>>& adj, int start, int target) {
if (start == target) return 0;
int nodes = adj.size();
vector<bool> visited(nodes, false);
queue<pair<int, int>> q;
visited[start] = true;
q.push({start, 0});
while (!q.empty()) {
auto curr = q.front();
q.pop();
for (int x : adj[curr.first]) {
if (x == target) {
return curr.second + 1;
}
if (!visited[x]) {
visited[x] = true;
q.push({x, curr.second + 1});
}
}
}
return -1;
}
int main() {
int n, m, s;
fin >> n >> m >> s;
vector<vector<int>> adj(n+1);
int x, y;
while (m--) {
fin >> x >> y;
adj[x].push_back(y);
}
vector<int> d(n+1, -1);
queue<int> q;
d[s] = 0;
q.push(s);
while (!q.empty()) {
int nod = q.front();
q.pop();
for (int x : adj[nod]) {
if (d[x] == -1) {
d[x] = d[nod] + 1;
q.push(x);
}
}
}
for (int i = 1; i <= n; ++i) {
fout << d[i] << ' ';
}
return 0;
}