有向邻接表的深度优先遍历
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define MAX_VERTEX_NUM 20
#define MAX_NAME 5
#define OK 1
#define TRUE 1
#define FALSE -1
typedef char VertexType[MAX_NAME];
typedef int InfoType;
using namespace std;
typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
InfoType *info;
}ArcNode;
typedef struct VNode
{
VertexType data;
ArcNode *firstarc;
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct
{ AdjList vertices;
int vexnum, arcnum;
int kind;
}ALGraph;
int LocateVex(ALGraph &G, VertexType &u)
{
for(int i = 0;i < G.vexnum; ++i)
{
if(strcmp(G.vertices[i].data,u) == 0)
return i;
}
return FALSE ;
}
int CreateDG( ALGraph &G )
{
int i,j,k,w;
VertexType v1,v2;
cout <<"开始构造有向图:\n请输入图的顶点的个数:";
cin >> G.vexnum;
cout << "请输入图的边的数目:";
cin >> G.arcnum;
cout <<"请输入所有的顶点:\n";
for(i = 0; i < G.vexnum; ++i)
{
cout << "请输入第"<< i+1 << "个顶点:";
scanf("%s",G.vertices[i].data);
G.vertices[i].firstarc = NULL;
}
cout <<"请输入弧,例如 v1-->v2\n";
for(k = 0; k < G.arcnum; ++k)
{
cout << "请输入第" << k+1 << "条弧的弧尾";
cin >> v1;
cout << "请输入第" << k+1 << "条弧的弧头";
cin >> v2;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
ArcNode *p;
p = (ArcNode *)malloc(sizeof(ArcNode));
if(!p)
{
cout << "Overflow";
return 0;
}
p->adjvex = j;
p->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc = p;
p->info = NULL;
}
return OK;
}
void DFS(ALGraph G, int v, int *visited)
{
ArcNode *p;
int w;
visited[v] = TRUE;
cout << G.vertices[v].data << "->";
for(p = G.vertices[v].firstarc; p != NULL; p = p->nextarc)
{
if(visited[p->adjvex] == 0)
{
visited[p->adjvex] = 0;
DFS(G, p->adjvex,visited);
}
}
}
void DFSTraverse( ALGraph &G )
{
int v;
int visited[MAX_VERTEX_NUM];
for( v = 0; v < G.vexnum; ++v )
visited[v] = 0;
for( v = 0; v < G.vexnum; ++v )
if(visited[v] == 0 )
DFS(G,v,visited);
}
void DestroyALGraph(ALGraph &G)
{
ArcNode *q;
for(int i = 0; i < G.vexnum; ++i)
for(ArcNode *p = G.vertices[i].firstarc; p != NULL;)
{
G.vertices[i].firstarc = NULL;
q = p;
p = p->nextarc;
free(q);
}
}
void main()
{
ALGraph G;
cout << endl << "DFSTraverse.cpp";
cout << endl << "===================" << endl;
CreateDG(G);
cout <<"深度优先搜索:\n";
DFSTraverse(G);
DestroyALGraph(G);
}