深度优先搜索与广度优先搜索———模板

/*无向图*/

#include
#include
#include
#include
using namespace std;
bool f[100],a[100][100];
int n,m,x,y;
void bfs(int t)
{
int k,closed,open,p[100]={0};
cout<" ";
open=0;
closed=1;
f[t]=1;
p[1]=t;
while (open<closed) 
{
open++;
k=p[open];
for (int i=1;i<=n;i++)
if (f[i]==0 && a[k][i])
{
cout<" ";
f[i]=1;
closed++;
p[closed]=i;
}
}
}
void dfs(int t)
{
cout<" ";
f[t]=1;
for (int i=1;i<=n;i++)
if (f[i]==0 && a[t][i]==1)
dfs(i);
}
int main()
{
cin>>n;
cin>>m;
memset(f,0,sizeof(f));
memset(a,0,sizeof(a));
for (int i=1;i<=m;i++)
{
cin>>x>>y;
a[x][y]=1;
a[y][x]=1;
}
dfs(1);
cout<<endl;
memset(f,0,sizeof(f));
bfs(1);
return 0;
}

 

转载于:https://www.cnblogs.com/xiaoqi7/p/5308460.html

你可能感兴趣的:(深度优先搜索与广度优先搜索———模板)