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
Output
0 3 4 2 5 1
Hint
用邻接表存储。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
int data;
struct node *next;
}*head[100], *p, *q;
int k;
int isbfs[100];
int queuebfs[100];
void sort(int k){
int t;
int i;
for(i = 0; i < k; i++){
for(p = head[i] -> next; p != NULL; p = p -> next){
for(q = p -> next; q != NULL; q = q -> next){
if(p -> data > q -> data){
t = p -> data;
p -> data = q -> data;
q -> data = t;
}
}
}
}
}
void bfs(int k){
int in, out;
int w;
int i;
in = out = 0;
queuebfs[in++] = k;
while(in > out){
w = queuebfs[out++];
for(p = head[w] -> next; p != NULL; p = p -> next){
if(isbfs[p -> data] == 0){
isbfs[p -> data] = 1;
printf(" %d", p -> data);
queuebfs[in++] = p -> data;
}
}
}
}
int main(){
int n;
int m, t;
int i;
int u, v;
scanf("%d", &n);
while(n--){
memset(isbfs, 0, sizeof(isbfs));
memset(queuebfs, 0, sizeof(queuebfs));
scanf("%d %d %d", &k, &m, &t);
for(i = 0; i < k; i++){
head[i] = (struct node *)malloc(sizeof(struct node));
head[i] -> next = NULL;
}
for(i = 0; i < m; 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;
q = (struct node *)malloc(sizeof(struct node));
q -> data = u;
q -> next = head[v] -> next;
head[v] -> next = q;
}
sort(k);
/*
for(i = 0; i < k; i++){
p = head[i] -> next;
while(p != NULL){
if(p -> next != NULL){
printf("%d ", p -> data);
}
else{
printf("%d\n", p -> data);
}
p = p -> next;
}
}
*/
isbfs[t] = 1;
printf("%d", t);
bfs(t);
printf("\n");
}
return 0;
}