Pagini recente » Cod sursa (job #504252) | Cod sursa (job #660392) | Cod sursa (job #939028) | Cod sursa (job #2858327) | Cod sursa (job #651252)
Cod sursa(job #651252)
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define max 100001
typedef struct node {
int info;
node *next;}node;
FILE *f;FILE *g;
node *list[max],*nod;
int c[max];int v[max];int D[max];
int n,m,i,u,p,x,s,y;
int main(){
f=fopen("bfs.in","r");
g=fopen("bfs.out","w");
fscanf(f,"%d",&n);
fscanf(f,"%d",&m);
fscanf(f,"%d",&s);
for (i=1;i<=m;i++)
{fscanf(f,"%d",&x);
fscanf(f,"%d",&y);
nod = (node *)malloc(sizeof(node));
nod->info = y;
nod->next = list[x];
list[x] = nod;}
c[1] = s;
v[s] = 1;u =1; p = 1;
while (p<=u)
{nod = list[c[p]];
while (nod!=NULL)
{if (v[nod->info]==0)
{u++;
c[u] = nod->info;
v[nod->info] = 1;
D[nod->info] = D[c[p]]+1;}
nod = nod->next;}
p++;}
int k=-1;
for(index=1;index<=n;index++)
if (v[index] == 0)
fprintf(g,"%d ",k);
else
fprintf(g,"%d",D[index]);
fclose(f);
fclose(g);free(nod);
return 0;}