数据结构实验之图论二:基于邻接表的广度优先搜索遍历

来源:互联网 发布:程序员的发展趋势 编辑:程序博客网 时间:2024/05/29 14:52

题目描述

给定一个无向连通图,顶点编号从0到n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)

输入

输入第一行为整数n(0< n <100),表示数据的组数。
对于每组数据,第一行是三个整数k,m,t(0<k<100,0<m<(k-1)*k/2,0< t<k),表示有m条边,k个顶点,t为遍历的起始顶点。 
下面的m行,每行是空格隔开的两个整数u,v,表示一条连接u,v顶点的无向边。

输出

输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。

示例输入

16 7 00 30 41 41 52 32 43 5

示例输出

0 3 4 2 5 1

提示

用邻接表存储。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cstdlib>
using namespace std;
struct node
{
   int data;
   struct node*next;
};
struct node*head[150];
int i,vis[150],w;
void bfs(int k,int m,int t)
{   struct node*p;
    queue<int>q;
    printf("%d",t);
    q.push(t);
    while(!q.empty())
    {
        w=q.front();
        q.pop();
        for(p=head[w]->next;p;p=p->next)//以元素做下标后面连着他的后继元素
        {
            if(!vis[p->data])
            {
               printf(" %d",p->data);
               vis[p->data]=1;
               q.push(p->data);
            }
        }

    }
}
int main()
{
    int n,k,m,t,u,v,nu;
    struct node*p,*q;
    scanf("%d",&n);
    while(n--)
    {
       scanf("%d%d%d",&k,&m,&t);
       memset(vis,0,sizeof(vis));
       for(i=0;i<k;i++)
       {
           head[i]=(struct node*)malloc(sizeof(struct node));
           head[i]->next=NULL;
       }
       for(i=0;i<=m-1;i++)
       {
           scanf("%d%d",&u,&v);
           p=(struct node*)malloc(sizeof(struct node));
           p->data=v;
           p->next=head[u]->next;
           head[u]->next=p;
           p=(struct node*)malloc(sizeof(struct node));
           p->data=u;
           p->next=head[v]->next;
           head[v]->next=p;//元素u的后面跟的都是他所连得元素
       }
       for(i=0;i<=k-1;i++)
       {
           for(p=head[i]->next;p;p=p->next)//优先遍历小节点
            for(q=p->next;q;q=q->next)
           {
               if(p->data>q->data)//这是链表如果对整个结构体进行交换指针就乱了
               {
                  nu=p->data;
                  p->data=q->data;
                  q->data=nu;
               }
           }
       }
       vis[t]=1;
       bfs(k,m,t);
    }
    return 0;
}

 

0 0
原创粉丝点击