Problem Description
给定一个无向连通图,顶点编号从0到n-1,用广度优先搜索(BFS)遍历,输出从某个顶点出发的遍历序列。(同一个结点的同层邻接点,节点编号小的优先遍历)
Input
输入第一行为整数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顶点的无向边。
Output
输出有n行,对应n组输出,每行为用空格隔开的k个整数,对应一组数据,表示BFS的遍历结果。
Sample Input
1 6 7 0 0 3 0 4 1 4 1 5 2 3 2 4 3 5
Sample Output
0 3 4 2 5 1
Hint
用邻接表存储。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int vertex;//结点数值
struct node *next;//指向下一结点
};
struct node *head[1000];//开辟顶点的指针数组
int visit[1000];//设置一个数组,用于检验该结点是否被访问过,若被访问过,则置为1;否则为零
int queue[1000];//设置队列
int front,rear;//设置队列头指针,尾指针
void add(struct node *head,int v)
{
struct node *p,*q,*r;
p=(struct node *)malloc(sizeof(struct node));
p->vertex=v;
p->next=NULL;//定义新结点
q=head;
r=head->next;
while(r!=NULL&&r->vertex<v)
{
q=r;
r=r->next;
}
q->next=p;
p->next=r;
}//按数值大小,在头结点后面增加新的结点
void BFS(int t)
{
int num;
struct node *p;
front=rear=0;
queue[front++]=t;
visit[t]=1;
printf("%d",t);
while(front>rear)
{
num=queue[rear++];
p=head[num]->next;
while(p!=NULL)
{
if(visit[p->vertex]==0)
{
printf(" %d",p->vertex);
visit[p->vertex]=1;
queue[front++]=p->vertex;
}
p=p->next;
}
}
}//利用队列存数值,指针进行访问
int main()
{
int n,m,k,t,i;
int v,u;
scanf("%d",&n);
for(i=0;i<=100;i++)
head[i]=(struct node *)malloc(sizeof(struct node));
while(n--)
{
memset(visit,0,sizeof(visit));
scanf("%d%d%d",&k,&m,&t);
for(i=0;i<=k-1;i++) head[i]->next=NULL;//头指针后均置为空
while(m--)
{
scanf("%d%d",&u,&v);
add(head[u],v);
add(head[v],u);
}//根据输入数值,建立邻接表
BFS(t);
}
return 0;
}