用邻接表存储。
#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; }
