Pagini recente » Cod sursa (job #36713) | Cod sursa (job #18592) | Cod sursa (job #1914258) | Cod sursa (job #1283216) | Cod sursa (job #2756080)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
int bfs(int n, vector<int> adj[], int st, int end) {
bool vis[n]{};
queue<pair<int, int>> Q;
Q.push({st, 0});
vis[st] = 1;
while(!Q.empty()) {
int currNode = Q.front().first, currDist = Q.front().second;
Q.pop();
if(currNode == end) {
return currDist;
}
for(int nxt : adj[currNode]) {
if(!vis[nxt]) {
Q.push({nxt, currDist + 1});
vis[nxt] = 1;
}
}
}
return -1;
}
const int nmax = 100000;
int n, m, s;
vector<int> adj[nmax];
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int main() {
fin >> n >> m >> s;
while(m--) {
int x, y;
fin >> x >> y;
adj[x - 1].push_back(y - 1);
}
for(int i = 0; i < n; i++) {
fout << bfs(n, adj, s - 1, i) << ' ';
}
fin.close();
fout.close();
return 0;
}