#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 100
int v[MAXSIZE];
int m[MAXSIZE][MAXSIZE];
int n,e;
void DFS(int k)
{
v[k]=1;
cout<<k<<" ";
for(int i=1;i<=n;i++)
if(!v[i]&&m[k][i])
DFS(i);
}
void BFS()
{
queue<int> q;
int k;
memset(v,0,sizeof(v));
for(int i=1;i<=n;i++)
if(!v[i])
{
v[i]=1;
cout<<i<<" ";
q.push(i);
while(!q.empty())
{
k=q.front();
q.pop();
for(int j=1;j<=n;j++)
if(!v[j]&&m[k][j])
{
v[j]=1;
cout<<j<<" ";
q.push(j);
}
}
}
}
int main()
{
int a,b;
cin>>n>>e;
memset(v,0,sizeof(v));
memset(m,0,sizeof(m));
for(int i=0;i<e;i++)
{
cin>>a>>b;
m[a][b]=m[b][a]=1;
}
cout<<"DFS:";
for(int i=1;i<=n;i++)
if(!v[i])
DFS(i);
cout<<endl;
cout<<"BFS:";
BFS();
}
![](https://i-blog.csdnimg.cn/blog_migrate/81fe57d45ed43398765b0be83316e444.png)
![](https://i-blog.csdnimg.cn/blog_migrate/248bc1b3e606c685aa397047ce25aefd.png)