代码实现:
#include<iostream>
#include<queue>
using namespace std;
#define MaxSize 10
#define inf 0x3f3f3f
int n,m;
bool book[MaxSize];
queue<int>q;
struct ArcNode{
int data;
ArcNode *next;
};
struct VNode{
ArcNode *next;
};
struct ALGraph{
VNode vex[MaxSize];
int vexsum,arcsum;
};
void bfs(ALGraph G,int x){
q.push(x);
book[x]=true;
while(!q.empty()){
cout<<q.front()<<" ";
ArcNode *p=G.vex[q.front()].next;
while(p!=NULL){
if(book[p->data]==false){
book[p->data]=true;
q.push(p->data);
}
p=p->next;
}
q.pop();
}
}
int main(){
cin>>n>>m;
ALGraph G;
G.vexsum=n;
G.arcsum=m;
for(int i=0;i<n;i++)
G.vex[i].next=NULL;
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
ArcNode *node=(ArcNode *)malloc(sizeof(ArcNode));
node->data=y;
node->next=G.vex[x].next;
G.vex[x].next=node;
ArcNode *node2=(ArcNode *)malloc(sizeof(ArcNode));
node2->data=x;
node2->next=G.vex[y].next;
G.vex[y].next=node2;
}
for(int i=0;i<n;i++){
book[i]=false;
}
for(int i=0;i<n;i++){
if(book[i]==false){
bfs(G,i);
}
}
return 0;
}
运行结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/be874b74d416bcc485a82e138e21dada.png)