#include<algorithm>
using namespace std;
const int maxsize=100;
bool visited[maxsize];
template <class Datatype>
class grahf
{
public:
grahf(Datatype a[],int n,int e);
~grahf();
void BFS(int v);
void DFS(int v);
private:
int bianshu,dianshu;
int bian[maxsize][maxsize];
Datatype dian[maxsize];
};
template <class Datatype>
grahf <Datatype>::~grahf()
{
dianshu=0;
bianshu=0;
}
template <class Datatype>
grahf <Datatype>::grahf(Datatype a[],int n,int e)
{
int i,j,k;
dianshu=n;
bianshu=e;
for(i=0;i<dianshu;i++)
{
dian[i]=a[i];
visited[i]=0;
}
for(i=0;i<dianshu;i++)
{
for(j=0;j<dianshu;j++)
{
bian[i][j]=0;
}
}
cout<<"依次输入边的两个端点"<<endl;
for(k=0;k<bianshu;k++)
{
cin>>i>>j;
bian[i][j]=1;
bian[j][i]=1;
}
}
template <class Datatype>
void grahf <Datatype>::DFS(int v)
{
int y;
cout<<dian[v]<<' ';
visited[v]=1;
for(y=0;y<dianshu;y++)
{
if(bian[v][y]==1 && visited[y]==0)
{
DFS(y);
//cout<<"565555";
}
}
}
template <class Datatype>
void grahf <Datatype>::BFS(int v)
{
Datatype Q[maxsize];
int front1=-1,rear=-1;
cout<<dian[v]<<' ';
visited[v]=1;
Q[++rear]=v;
while(front1!=rear)
{
v=Q[++front1];
for(int j=0;j<dianshu;j++)
{
if(bian[v][j]==1 && visited[j]==0)
{
cout<<dian[j]<<' ';
visited[j]=1;
Q[++rear]=j;
}
}
}
}
int main()
{
cout<<"****1.DFS 2.BFS 3.退出****"<<endl;
while(1)
{
cout<<"输入你的选择"<<endl;
int x;
cin>>x;
if(x==1)
{
int a[maxsize];
int o;//点数
int k;//边数
cout<<"输入图的点数和边数"<<endl;
cin>>o>>k;
cout<<"输入图的点"<<endl;
for(int i=0;i<o;i++)
{
cin>>a[i];
}
grahf <int> G(a,o,k);
cout<<"广度优先遍历为:";
G.DFS(1);
cout<<endl;
}
else if(x==2)
{
int a[maxsize];
int o;//点数
int k;//边数
cout<<"输入图的点数和边数"<<endl;
cin>>o>>k;
cout<<"输入图的点"<<endl;
for(int i=0;i<o;i++)
{
cin>>a[i];
}
grahf <int> G(a,o,k);
cout<<"深度优先遍历为:";
G.BFS(0);
cout<<endl;
}
else if(x==3)
{
cout<<"退出程序"<<endl;
break;
}
else
{
cout<<"输入异常,退出"<<endl;
break;
}
}
return 0;
}
图的深度遍历和广度遍历
本文详细介绍了图的两种经典遍历方法——深度优先搜索(DFS)和广度优先搜索(BFS),包括它们的基本原理、实现步骤及应用场景。通过实例解析,帮助读者理解这两种遍历策略在解决实际问题中的重要作用。
摘要由CSDN通过智能技术生成