越发的发现,自己对链表的不熟悉。写dfs、bfs写了无数次,结果用链表写的时候居然迟疑了。。
多多加强对链表的运用啊!
/*
图的深度、广度优先搜索(邻接表存储)
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <string.h>
using namespace std;
struct ArcNode
{
ArcNode *nextarc;
int id;
int weight;
};
struct VexNode
{
ArcNode *firstarc;
int id;
};
class Graph
{
private:
int n;
int max;
VexNode *adjlist;
bool *visit;
public:
Graph( int l )
{
n=0; max=l;
adjlist=new VexNode[l];
visit=new bool[l];
}
~Graph()
{
delete []adjlist;
delete []visit;
}
void instArc( int a,int b,int w=0 );
void instVex( int a );
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::instVex( int a )
{
if( n<max )
{
adjlist[n].id=a;
adjlist[n++].firstarc=NULL; //置空勿忘
}
}
void Graph::instArc( int a,int b,int w ) //不带等于0
{
ArcNode *p=new ArcNode;
ArcNode *q=new ArcNode;
p->id=b;
q->id=a;
p->nextarc=adjlist[a].firstarc;
q->nextarc=adjlist[b].firstarc;
adjlist[a].firstarc=p;
adjlist[b].firstarc=q;
}
string Graph::dfs0( int sta,string s )
{
ArcNode *p;
s+=( adjlist[sta].id+'0' );
s+=' ';
if( adjlist[sta].firstarc==NULL ) return s;
p=adjlist[sta].firstarc;
while( p!=NULL )
{
if( !visit[p->id] )
{
visit[p->id]=1;
s=dfs0( p->id,s );
}
p=p->nextarc;
}
return s;
}
string Graph::dfs( int sta,string s ) //dfs操作接口
{
memset( visit,0,sizeof(visit) );
visit[sta]=1;
return "深度优先:"+dfs0( sta,s );
}
string Graph::bfs0( int sta,string s )
{
ArcNode *p;
int top,last;
int stack[100];
top=0; last=1;
stack[0]=sta;
s+=( sta+'0' );
s+=' ';
visit[sta]=1;
while( top<last )
{
p=adjlist[ stack[top] ].firstarc;
++top;
while( p!=NULL )
{
if( !visit[p->id] )
{
s+=( p->id+'0' );
s+=' ';
visit[p->id]=1;
stack[last++]=p->id;
}
p=p->nextarc;
}
}
return s;
}
string Graph::bfs( int sta,string s ) //bfs操作接口
{
memset( visit,0,sizeof(visit) );
return "广度优先:"+bfs0( sta,s );
}
int main()
{
Graph g(10);
int i;
for( i=0;i<4;i++ ) g.instVex(i);
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;
}