邻接矩阵这个写的多了。。
/*
图的深度、广度优先搜索(邻接矩阵存储)
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <string.h>
using namespace std;
class Graph
{
private:
int adj[100][100];
int max;
bool *visit;
public:
Graph(int l)
{
int i,j;
for( i=0;i<l;i++ )
for( j=0;j<l;j++ )
adj[i][j]=0;
max=l;
visit=new bool[l];
}
void instArc( int a,int b );
string dfs( int sta,string s );
string dfs0( int sta,string s );
string bfs( int sta,string s );
string bfs0( int sta,string s );
};
void Graph::instArc(int a,int b)
{
adj[a][b]=1;
adj[b][a]=1;
}
string Graph::dfs0( int sta,string s )
{
int i;
s+=( sta+'0' );
s+=' ';
for( i=0;i<max;i++ )
{
if( !visit[i] && adj[sta][i] )
{
visit[i]=1;
s=dfs0( i,s );
}
}
return s;
}
string Graph::dfs( int sta,string s )
{
memset( visit,0,sizeof(visit) );
visit[sta]=1;
return "深度优先:"+dfs0( sta,s );
}
string Graph::bfs0( int sta,string s )
{
int top,i;
int stack[100];
top=0;
stack[top]=sta;
s+=( sta+'0' );
s+=' ';
while( top>=0 )
{
sta=stack[top];
top--;
for( i=0;i<max;i++ )
{
if( !visit[i] && adj[sta][i] )
{
s+=( i+'0' );
s+=' ';
visit[i]=1;
stack[++top]=i;
}
}
}
return s;
}
string Graph::bfs( int sta,string s )
{
memset( visit,0,sizeof(visit) );
visit[sta]=1;
return "广度优先:"+bfs0( sta,s );
}
int main()
{
Graph g(10);
g.instArc(0,1);
g.instArc(0,2);
g.instArc(3,1);
g.instArc(3,2);
cout<<g.dfs(0,"")<<endl;
cout<<g.bfs(0,"")<<endl;
return 0;
}