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顶点的无向边。
对于每组数据,第一行是三个整数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 <math.h>
#define SH struct H *
#define SH1 struct H
int n,k,m,t;
int vis[105];
int s[105];
struct H
{
int data;
struct H *next;
}*head[105];
void getline(int a,int b)
{
struct H *p,*r,*q;
p=(SH)malloc(sizeof(SH1));
r=(SH)malloc(sizeof(SH1));
q=(SH)malloc(sizeof(SH1));
p=head[a]->next;
q=head[a];
r->data=b;
while(p!=NULL)
{
if(r->data<p->data)
{
r->next=q->next;
q->next=r;
break;
}
q=p;
p=p->next;
}
if(p==NULL)
{
r->next=q->next;
q->next=r;
}
}
void BFS()
{
int x,y,j,d;
struct H *p;
p=(SH)malloc(sizeof(SH1));
int enter,out;
enter=1;
out=0;
s[0]=t;
vis[t]=1;
while(out<enter)
{
d=s[out++];
p=head[d]->next;
while(p!=NULL)
{
j=p->data;
if(!vis[j])
{
s[enter++]=j;
vis[j]=1;
}
p=p->next;
}
}
}
int main()
{
int i,j;
int a,b;
struct H *p;
p=(SH)malloc(sizeof(SH1));
scanf("%d",&n);
while(n--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d%d",&k,&m,&t);
for(i=0; i<k; i++)
{
head[i]=(SH)malloc(sizeof(SH1));
head[i]->next=NULL;
}
while(m--)
{
scanf("%d%d",&a,&b);
getline(a,b);
getline(b,a);
}
BFS();
for(i=0; i<k; i++)
{
printf("%d ",s[i]);
}
printf("\n");
}
return 0;
}