Pagini recente » Cod sursa (job #2600659) | Cod sursa (job #2449110) | Cod sursa (job #1149638) | Cod sursa (job #601818) | Cod sursa (job #2796964)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define N 100005
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
bool viz[N];
int cost[N];
class Graph {
public:
int n; //nr de varfuri
int m; //nr de muchii
vector <int> a[N];
Graph(int n, int m)
{
this->n = n;
this->m = m;
}
void Citire_orientat()
{
int i;
int x, y;
for (i = 0; i < m; i++)
{
fin >> x >> y;
a[x].push_back(y);
}
}
void BFS(int x);
};
void Graph::BFS(int x)
{
queue <int> q;
int k, i;
viz[x] = 1;
cost[x] = 0;
q.push(x);
while (!q.empty())
{
k = q.front();
for (i = 0; i < a[k].size(); i++)
if (!viz[a[k][i]])
{
q.push(a[k][i]);
viz[a[k][i]] = 1;
cost[a[k][i]] = cost[k] + 1;
}
q.pop();
}
for (i = 1; i <= n; i++)
if (viz[i] == 0)
fout << -1 << " ";
else fout << cost[i] << " ";
}
int main()
{
int n, m, S;
fin >> n >> m >> S;
Graph g(n, m);
g.Citire_orientat();
g.BFS(S);
return 0;
}