实现代码:
#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;
}
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;
}
运行结果:
|