zoukankan      html  css  js  c++  java
  • 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("
    ");
    }
    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);
        }
    }
    
  • 相关阅读:
    HDU 4350 Card
    HDU 4287 Intelligent IME
    POJ Stars
    字符串处理
    NYOJ 63 小猴子下落
    在 DataGrid 控件中显示 SQL Server 数据库中的数据
    Linq to sql学习之查询句法
    SqlMethods
    SQLSERVER 2008 R2中的全文检索
    分享学习网站大全
  • 原文地址:https://www.cnblogs.com/yspworld/p/4158374.html
Copyright © 2011-2022 走看看