• 基于邻接表的广度优先搜索遍历


    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    int k,h[110],mark;
    
    struct M
    {
        int data;
        struct M *next;
    }*head[110];
    
    void init()
    {
        int i;
        for(i = 0; i < k; i++)
        {
            head[i] = (struct M *)malloc(sizeof(struct M));
            head[i]->next = NULL;
            head[i]->data = -1;
        }
    }
    
    void link(int u,int v)
    {
        struct M *p1,*p2,*q;
        q = (struct M *)malloc(sizeof(struct M));
        q->next = NULL;
        q->data = v;
        for(p1 = head[u],p2 = p1->next; p2 != NULL; p1 = p1->next,p2 = p2->next)
        {
            if(p1->data < v && p2->data > v)
            {
                q->next = p1->next;
                p1->next = q;
                return;
            }
            else if(p2->data == v)
            {
                free(q);
                return;
            }
        }
        p1->next = q;
    }
    
    void seek(int mb)
    {
        struct M *p;
        int q[105],s,e;
        s = e = 0;
        q[e++] = mb;
        while(s < e)
        {
            mb = q[s++];
            if(mark)
            {
                mark = 0;
                printf("%d",mb);
            }
            else printf(" %d",mb);
            for(p = head[mb]->next; p != NULL; p = p->next)
            {
                if(!h[p->data])
                {
                    h[p->data] = 1;
                    q[e++] = p->data;
                }
            }
        }
    }
    
    int main()
    {
        int js,m,t,i,u,v;
        struct M *p;
        scanf("%d",&js);
        while(js--)
        {
            scanf("%d %d %d",&k,&m,&t);
            init();
            for(i = 0; i < m; i++)
            {
                scanf("%d %d",&u,&v);
                link(u,v);
                link(v,u);
            }
            memset(h,0,sizeof(h));
            h[t] = 1;
            mark = 1;
            seek(t);
            printf("\n");
        }
        return 0;
    }
  • 相关阅读:
    Spring 原生SQL查询
    Spring 使用注解查询 JPQL 按对象查询
    JAVA 判断输入流是否为空
    Spring-AOP教程
    错误笔记5, Spring datatable Error creating bean with name 'userController'
    Spring 分页查询
    前端传数据到servlet数据乱码
    sql 分页查询
    移动APP性能测试
    【8】接口、多态
  • 原文地址:https://www.cnblogs.com/zmx354/p/2934064.html
Copyright © 2020-2023  润新知