# Cod sursa(job #223158)

Utilizator Data 27 noiembrie 2008 01:10:51 BFS - Parcurgere in latime Ascuns cpp done 1.06 kb
``````#include <stdio.h>
#include <vector>

using namespace std;

#define maxn 100010

int N, M, L, Start;
vector <int> A[maxn];
int G[maxn], S[maxn], Cost[maxn];

void BFS(int nod)
{
int i, j;

memset(Cost, -1, sizeof(Cost));  //	Marchez toate nodurile ca fiind nevizitate

//	Introduc nodul de start in coada
L = 1;
Cost[nod] = 0;
S[L] = nod;

for (i = 1; i <= L; i++)	//	Elimin pe rand nodurile din coada
for (j = 0; j < G[S[i]]; j++)	//	Parcurg vecinii nodului ce urmeaza sa fie eliminat
if (Cost[A[S[i]][j]] == -1)
{
S[++L] = A[S[i]][j];
Cost[S[L]] = Cost[S[i]] + 1;
}
}

int main()
{
freopen("bfs.in", "r", stdin);
freopen("bfs.out", "w", stdout);

int i, x, y;

scanf("%d %d %d ", &N, &M, &Start);

//	Citesc arcele si retin graful sub forma de lista de vecini

for (i = 1; i <= M; i++)
{
scanf("%d %d ", &x, &y);
A[x].push_back(y);
}

for (i = 1; i <= N; i++)
G[i] = A[i].size();

BFS(Start);

for (i = 1; i <= N; i++)
printf("%d ", Cost[i]);
printf("\n");

return 0;
}
``````