代码实现:
#include<iostream>
#include<queue>
using namespace std;
#define MaxSize 10
#define inf 0x3f3f3f
bool book[MaxSize];
int n,m;
queue<int>q;
struct MGraph{
int edge[MaxSize][MaxSize];
int vexnum,arcnum;
};
int FirstNeighbor(MGraph G,int x){
for(int i=0;i<n;i++){
if(G.edge[x][i]=1)
return i;
}
return -1;
}
int NextNeighbor(MGraph G,int x,int j){
for(int i=j+1;i<n;i++){
if(G.edge[x][i]==1)
return i;
}
return -1;
}
void bfs(MGraph G,int x){
q.push(x);
book[x]=true;
while(!q.empty()){
cout<<q.front()<<" ";
for(int i=FirstNeighbor(G,q.front());i>=0;i=NextNeighbor(G,q.front(),i)){
if(book[i]==false){
book[i]=true;
q.push(i);
}
}
q.pop();
}
}
int main(){
cin>>n>>m;
MGraph G;
G.vexnum=n;
G.arcnum=m;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j){
G.edge[i][j]=0;
}
else{
G.edge[i][j]=inf;
}
}
}
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
G.edge[x][y]=1;
}
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;
}
运行结果: