实现代码:
#include<iostream>
#include<queue>
using namespace std;
#define MaxSize 10
#define inf 0x3f3f3f
bool book[MaxSize];
int n,m;
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 dfs(MGraph G,int x){
cout<<x<<" ";
book[x]=true;
for(int i=FirstNeighbor(G,x);i>=0;i=NextNeighbor(G,x,i)){
if(book[i]==false){
book[i]=true;
dfs(G,i);
}
}
}
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)
dfs(G,0);
}
return 0;
}
运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/a4ba0335e36144849152ceb360fade78.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBAbHN55ZCM5a2m,size_46,color_FFFFFF,t_70,g_se,x_16)