Pagini recente » Cod sursa (job #1818144) | Cod sursa (job #1302732) | Cod sursa (job #473694) | Cod sursa (job #2350508) | Cod sursa (job #2489688)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 100005
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector <int> ListAdiacenta[NMAX];
queue <int> Q;
int Cost[NMAX], Vec[NMAX];
int Node, N, M;
void BFS(int start)
{
memset(Cost,-1,sizeof(Cost));
Q.push(start);
Cost[start] = 0;
while(!Q.empty())
{
int curr = Q.front();
for(int i = 0; i < Vec[curr]; i++)
if(Cost[ListAdiacenta[curr][i]] == -1)
{
Q.push(ListAdiacenta[curr][i]);
Cost[ListAdiacenta[curr][i]] = Cost[curr] + 1;
}
Q.pop();
}
}
int main()
{
int x, y;
fin >> N >> M >> Node;
for(int i = 1; i <= M; i++)
{
fin >> x >> y;
ListAdiacenta[x].push_back(y);
}
for(int i = 1; i <= N; i++)
Vec[i] = ListAdiacenta[i].size();
BFS(Node);
for(int i = 1; i <= N; i++)
fout << Cost[i] << " ";
fout << "\n";
fin.close();
fout.close();
return 0;
}