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
代码(用临接表做):
#include<stdio.h> #include<string.h> #include<stdlib.h> int vis[101]; int n,m,k;int shu[100],sh=1; struct node { int u,v; struct node *next; }*head[110]; void add(int u, int v) { struct node *p = (struct node*)malloc(sizeof(struct node)); p->u = u; p->v = v; p->next = head[u]; head[u] = p; }; void bfs(int t) {vis[t]=1; struct node *p; p=(struct node*)malloc(sizeof(struct node)); p=head[t]; int b[100],s=1; while(p!=NULL) { if(vis[p->v]==0) {b[s++]=p->v; vis[p->v]=1; p=p->next;} else p=p->next; } for(int i=1;i<s-1;i++) for(int j=i+1;j<s;j++) if(b[i]>b[j]) { int t; t=b[i]; b[i]=b[j]; b[j]=t; } for(int i=1;i<s;i++) printf(" %d",b[i]); for(int i=1;i<s;i++) bfs(b[i]); } int main() { int t,i,u,v; scanf("%d",&n); while(n--) { memset(head,NULL,sizeof(head)); memset(vis,0,sizeof(vis)); scanf("%d %d %d",&k,&m,&t); for(i=0; i<m; i++) { scanf("%d %d",&u,&v); add(u,v); add(v,u); } printf("%d",t); bfs(t); printf("\n"); } return 0; }