bfs 邻接表

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    int date;
    struct node *next;

}*h[1000],*head[1000];
int v[10000],vi[10000];
int i,j;
int t,n,m,k;
void chu(int z)
{
    for(i=0;i<z;i++)
    {h[i]=(struct node*)malloc(sizeof(struct node));
        h[i]->next=NULL;
        head[i]=h[i];
    }


}
void chu1(int z)
{
 for(i=0;i<z;i++)
    {
        head[i]=head[i]->next;
    }}
void bfs(int K)
{
    int jin=0,chu=0;
    chu1(n);
     int w;
    v[jin++]=K;
    vi[K]=2;
    printf("%d",K);
    while(chu<jin)
    {w=v[chu++];
    if(chu!=1&&vi[w]==1)
        {printf(" %d",w);
        vi[w]=2;}
        while(head[w]!=NULL)
        {
            if(vi[head[w]->date]==0)
            {
        v[jin++]=head[w]->date;vi[head[w]->date]=1;
        }
            head[w]=head[w]->next;
        }

    }
    printf("\n");
}
int main()
{

    node *p,*q;
    scanf("%d",&t);
    for(i=0;i<t;i++)
    {
        scanf("%d%d%d",&n,&m,&k);
        chu(n);
        memset(vi,0,sizeof(vi));
        for(j=0;j<m;j++)
        {
          int a,b;
          scanf("%d%d",&a,&b);
          p=(struct node*)malloc(sizeof(struct node));
        p->next=NULL;
        p->date=b;
        h[a]->next=p;
        h[a]=p;
          p=(struct node*)malloc(sizeof(struct node));
        p->next=NULL;
        p->date=a;
        h[b]->next=p;
        h[b]=p;
        }
        bfs(k);
    }
}

 

posted @ 2014-12-11 19:53  我喜欢旅行  阅读(224)  评论(0编辑  收藏  举报