#include<iostream.h>
const MAX_VERTEX_NUM=20;
bool visited[10];
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
int data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
int LocateVex(ALGraph &G,int V)
{
int a;
a=V;
return a;
}
void CreateUDG(ALGraph &G)
{
ArcNode *pi,*pj;
int j;
int v1,v2;
cout<<"请输入结点数与弧的数目:\n";
cin>>G.vexnum>>G.arcnum;
cout<<"输入顶点的值:\n";
for(int i=0;i<G.vexnum;++i)
{
cin>>G.vertices[i].data;
G.vertices[i].firstarc=NULL;
}
cout<<"输入弧的始点与终点:\n";
for(int k=0;k<G.arcnum;++k)
{
cin>>v1>>v2;
i=LocateVex(G,v1);
j=LocateVex(G,v2);
pi=new ArcNode;
pi->adjvex=j;
pi->nextarc=G.vertices[i].firstarc;
G.vertices[i].firstarc=pi;
pj=new ArcNode;
pj->adjvex=i;
pj->nextarc=G.vertices[j].firstarc;
G.vertices[j].firstarc=pj;
}
}
void DFS(ALGraph &G,int v)//深度遍历
{
ArcNode *p;
int w;
visited[v]=true;
cout<<G.vertices[v].data<<'\n';
for(p=G.vertices[v].firstarc;p;p=p->nextarc)
{
w=p->adjvex;
if(!visited[w])
DFS(G,w);
}
}
void DFSTraverse(ALGraph &G)
{
cout<<"遍历的结果为:\n";
for(int v=0;v<G.vexnum;v++)
visited[v]=false;
for(v=0;v<G.vexnum;v++)
if(!visited[v])
DFS(G,v);
}
void main()
{
ALGraph G;
CreateUDG(G);
DFSTraverse(G);
}