Cod sursa(job #649766)

Utilizator FIIAndCocRotAndrei Alexandra FIIAndCocRot Data 16 decembrie 2011 18:00:44
Problema BFS - Parcurgere in latime Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.27 kb
#include<stdio.h>
#include<stdlib.h>

#define MAX 100003

FILE *f, *g;

int N, M, S, queque[MAX],  viz[MAX], first, last, cost[MAX], index;


typedef struct Node 
{	int info; 
	struct Node *next;
} Node;
Node *a[MAX];

void file_open ()
{	f=fopen("bfs.in", "r");
	g=fopen("bfs.out", "w");
}

void write ()
{	for(index=1;index<=N;index++)
	fprintf(g, "%d ", cost[index]);
}

void file_close ()
{	fclose (f);
	fclose(g);
}

int add_bow (int n1, int n2)
{	Node *ptr;
	if(!(ptr=(Node*)malloc(sizeof(Node))))
		return 0;
	ptr->info=n2;
	ptr->next=a[n1];
	a[n1]=ptr;
	return 1;
}

void read_node ()
{ 	int n1, n2;
	for(index=0; index<M; index++)
	{fscanf(f,"%d%d", &n1, &n2);
	 if(!(add_bow(n1,n2)))
		{printf("eroare");
		 return ;
		}
	}
}

void BFS()
{	Node *p;
	viz[S]=1;
	queque[last]=S;
	cost[S]=0;
	last=1;
	for(first=0; first<last; first++)
   	{for(p=a[queque[first]]; p!=NULL; p=p->next)
     		{if(viz[p->info]==0)
			{queque[last]=p->info;
		 	 viz[p->info]=1;
			 cost[queque[last]]=cost[queque[first]]+1;
			 last++;
			}
		}
	}

}	

int main ()
{	file_open();
	fscanf(f,"%d %d %d", & N, &M, &S);
	read_node();
	for(index=0; index<=N; index++)
		cost[index]=-1;
	BFS();
	write();
	file_close();
	return 0;
}