Pagini recente » Cod sursa (job #1124849) | Cod sursa (job #104311) | Cod sursa (job #1186687) | Cod sursa (job #2904043) | Cod sursa (job #2019124)
#include <fstream>
#include <iostream>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
struct el
{
int info;
el *next;
};
el *nods[100005], *p, *q;
el *head, *curent, *another;
int distanta[100005], n, m, s, nodX, nodY, pas;
void Adauga_Vecin(int x, int y)
{
q = new el;
q -> info = y;
q -> next = nods[x];
nods[x] = q;
}
void Adauga_inCoada(int nod)
{
another = new el;
another -> info = nod;
another -> next = NULL;
curent -> next = another;
curent = another;
}
void Pop()
{
el *aux;
aux = head;
head = head -> next;
delete aux;
}
void BFS()
{
while(head != NULL)
{
int nodcurent = head -> info;
for(p = nods[nodcurent]; p != NULL; p = p -> next)
{
if(distanta[p -> info] == -1)
{
Adauga_inCoada(p -> info);
distanta[p -> info] = distanta[nodcurent] + 1;
}
}
Pop();
}
}
int main()
{
f >> n >> m >> s;
for(int i = 1; i <= m; ++i)
{
f >> nodX >> nodY;
if(nodX != nodY) Adauga_Vecin(nodX, nodY);
}
for(int i = 1; i <= n; ++i) distanta[i] = -1;
distanta[s] = 0;
head = new el;
head -> info = s;
head -> next = NULL;
curent = head;
BFS();
for(int i = 1; i <= n; ++i) g << distanta[i] << " ";
return 0;
}