Pagini recente » Cod sursa (job #3211110) | Cod sursa (job #1665116) | Cod sursa (job #1222926) | Cod sursa (job #1758821) | Cod sursa (job #2633169)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int NMAX = 100005;
int n, m, Distance[NMAX];
vector < int > edges[NMAX];
queue < int > Q;
/// 0 -> start node, -1 -> we can't reach it
void BFS()
{
int node, neighbour;
while (!Q.empty()){
node = Q.front();
Q.pop();
for (unsigned int i = 0; i < edges[node].size(); i++){
neighbour = edges[node][i];
if (Distance[neighbour] == -1){
Q.push(neighbour);
Distance[neighbour] = Distance[node] + 1;
}
}
}
}
void read()
{
int nodeStart;
fin >> n >> m >> nodeStart;
for (int i = 1; i <= m; i++){
int x, y;
fin >> x >> y;
edges[x].push_back(y);
}
for (int i = 1; i <= n; i++)
Distance[i] = -1;
Distance[nodeStart] = 0;
Q.push(nodeStart);
BFS();
for (int i = 1; i <= n; i++)
fout << Distance[i] << " ";
}
int main()
{
read();
return 0;
}