Pagini recente » Cod sursa (job #2781261) | Cod sursa (job #2711801) | Cod sursa (job #1923134) | Cod sursa (job #431416) | Cod sursa (job #2900296)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int N = 10000;
vector <int> a[N+1];
int d[N+1], n;
void init_d(int d[])
{
for (int i = 1; i <= n; i++)
{
d[i] = -1;
}
}
void bfs (int x0, int d[])
{
init_d(d);
queue <int> q;
q.push(x0);
d[x0] = 0;
while (!q.empty())
{
int x = q.front();
q.pop();
for (auto y: a[x])///y va parcurge elementele lui a[x]
{
if (d[y] == -1)
{
q.push(y);
d[y] = 1 + d[x];
}
}
}
}
int main ()
{
ifstream in("bfs.in");
ofstream out("bfs.out");
int m, s;
in >> n >> m >> s;
for (int i = 0; i < m; i++)
{
int x, y;
in >> x >> y;
//a[x][y] = a[y][x] = true;
a[x].push_back(y);///il adauga pe y la sfarsitul listei de adiacenta a lui x (a[x])
//a[y].push_back(x);///il adauga pe y in lista lui x
}
in.close();
bfs(s,d);
for (int i = 1; i <= n; i++)
{
out << d[i] << " ";
}
out.close();
return 0;
}