#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int n,m,v[11],Map[11][11];
//用广度优先和深度优先搜素实现求联通分量
//结点从0开始命名
//map数组是图的关系矩阵,v数组是是否遍历过
void DFS(int x)//深度优先:操作当下(打印)->找到下一个
{
cout<<' '<<x;
for(int i=0; i<n; i++)
{
if(!v[i]&&Map[x][i]==1)
{
v[i]=1;//注意,一定是先标记遍历过,再去递归搜索
DFS(i);
}
}
}
void BFS(int x)//广度优先搜索:初始化队列后,拿出队头(并打印),把有联系的元素全部入队
{
int y;
queue<int> Q;
Q.push(x);
while(!Q.empty())
{
y=Q.front();
cout<<' '<<y;
Q.pop();
for(int i=0;i<n;i++)
{
if(!v[i]&&Map[y][i]==1)
{
v[i]=1;//入队列之前一定要先标记
Q.push(i);
}
}
}
}
int main()
{
int x,y;
cout<<"Please input two fingures,one represents the count of node,the other present the count of link"<<endl;
cin>>n>>m;
memset(Map,0,sizeof(Map));
memset(v,0,sizeof(v));
cout<<"Please input corresponding arrays prensents linkage,each array contain two figures,and each fingure must be limited in the first figure you input just now"<<"\n";
while(m--)
{
cin>>x>>y;
Map[x][y]=Map[y][x]=1;
}
cout<<"This is results of DFS:"<<endl;
for(int i=0;i<n;i++)
{
if(v[i]==0)//对每个没有遍历过的结点进行深度优先搜素
{
v[i]=1;
cout<<"{";
DFS(i);
cout<<"}"<<endl;
}
}
memset(v,0,sizeof(v));
cout<<"This is results of BFS:"<<endl;
for(int i=0; i<n; i++)
{
if(v[i]==0)
{
v[i]=1;
cout<<"{";
BFS(i);
cout<<"}"<<endl;
}
}
return 0;
}