好吧。。这是最基础的代码,刚学会的。=w=
#include <iostream>
using namespace std;
#define MAX_VERTEX_NUM 20
struct ArcNode{
int adjvex;
ArcNode *nectarc;
};
struct VexNode{
int data;
ArcNode *firstarc;
};
struct Graph{
VexNode vertices[MAX_VERTEX_NUM];
int vexnum,arcnum;
};
bool ListInsert(VexNode *L,int i,ArcNode e){
int j=0;
ArcNode *s,*t;
s=new ArcNode();
s->adjvex=e.adjvex;
VexNode *p=L;
if (!p||j>i-1)
return false;
if (i==1){
s->nectarc=p->firstarc;
p->firstarc=s;
}
else {
t=p->firstarc;
while (j<i-1){
t=t->nectarc;
}
s->nectarc=t->nectarc;
t->nectarc=s;
}
return true;
}
void CreateGraph(Graph *G){
int i,j,k;
int va,vb;
ArcNode e;
cout<<"输入图的顶点数、边数:";
cin>>(*G).vexnum>>(*G).arcnum;
for (i=0;i<(*G).vexnum;i++){
(*G).vertices[i].data=i;
(*G).vertices[i].firstarc=NULL;
}
cout<<"输入弧头弧尾:"<<endl;
for (k=0;k<(*G).arcnum;k++){
cin>>va>>vb;
e.adjvex=va;
ListInsert(&(*G).vertices[vb],1,e);
e.adjvex=vb;
ListInsert(&(*G).vertices[va],1,e);
}
}
bool visited[MAX_VERTEX_NUM];
void VisitFunc(int v){
cout<<v<<' ';
}
void DFS(Graph G,int v){
int w;
ArcNode *p;
visited[v]=true;
VisitFunc(G.vertices[v].data);
p=G.vertices[v].firstarc;
while (p){
w=p->adjvex;
if (!visited[w])
DFS(G,w);
p=p->nectarc;
}
}
void DFSTraverse(Graph G){
int v;
for (v=0;v<G.vexnum;v++)
visited[v]=false;
for (v=0;v<G.vexnum;v++)
if (!visited[v])
DFS(G,v);
}
int main(){
Graph G;
CreateGraph(&G);
DFSTraverse(G);
return 0;
}