Pagini recente » Cod sursa (job #399123) | Cod sursa (job #2062295) | Cod sursa (job #110674) | Cod sursa (job #2735579) | Cod sursa (job #923441)
Cod sursa(job #923441)
#include<queue>
#include<fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int a[10000][10000], marc[10000], cost[10000], s, n, m;
queue <int> q;
int bfs(int start) {
int i, x;
cost[start] = 0;
marc[start] = 1;
q.push(start);
while (!q.empty()) {
x = q.front();
q.pop();
for (i = 1; i <= n; i++) {
if (a[x][i] == 1 and not marc[i]) {
q.push(i); marc[i] = 1; cost[i] = cost[x] + 1;
}
}
}
}
void setcost() {
int i;
for (i = 1; i <= n; i++)
cost[i] = -1;
}
void afiscost() {
int i;
for (i = 1; i <= n; i++)
fout << cost[i] << " ";
}
int main() {
int i, x, y;
fin >> n >> m >> s;
for (i = 1; i <= m; i++) {
fin >> x >> y;
a[x][y] = 1;
}
setcost();
bfs(s);
afiscost();
}