#include "stdio.h"
#include "stdlib.h"
#define MAX 20
#define OK 1
#define ERROR -1
typedef char InfoType;
typedef char VertexType ;
typedef int (*Visit)(int n);
int visited[MAX];
typedef struct ArcNode
{
int adjvex;
struct ArcNode*nextarc;
//InfoType *info;
}ArcNode;//结点结构
typedef struct VNode
{
VertexType data;//顶点数据域
ArcNode *firstarc;
}VNode,AdjList[MAX];//顶点结构
typedef struct{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;//图结构
int LocateVex(ALGraph G,VertexType v1)
{
for(int i=0;i<G.vexnum;i++)
{
if(G.vertices[i].data==v1)
return i;
}
return ERROR;
}
void my_getchar(char*a,char*b)
{
*a=getchar();
getchar();
*b=getchar();
getchar();
}
int CreateDG(ALGraph *G)
{
int i,j;
char v1,v2;
printf("CreateDG(ALGraph*G)/n");
printf("Input Graph 顶点个数,顶点个数:");
scanf("%d,%d",&(*G).vexnum,&(*G).arcnum);getchar();
for(int k=0;k<(*G).vexnum;++k)
{
printf("input Node data:");
scanf("%c",&(*G).vertices[k].data); getchar();
(*G).vertices[k].firstarc=NULL;
}
for(k=0;k<(*G).arcnum;k++)
{
printf("input V1 ,V2/n");
scanf("%c,%c",&v1,&v2);getchar();
i=LocateVex(*G,v1);j=LocateVex(*G,v2);
ArcNode *p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=j;
p->nextarc=(*G).vertices[i].firstarc;
(*G).vertices[i].firstarc=p;
}
return OK;
}
void my_print(ALGraph G)//打印邻接表
{
ArcNode *p=NULL;
for(int i=0;i<G.vexnum;i++)
{
printf(" %d head:%c ",i,G.vertices[i].data);
p=G.vertices[i].firstarc;
while(p)
{
printf("-->%d",p->adjvex);
p=p->nextarc;
}
printf("/n");
}
}
int FirstAdjVex(ALGraph G,int i)
{
return G.vertices[i].firstarc
?G.vertices[i].firstarc->adjvex:-1;
}
int NextAdjVex(ALGraph G,int v,int w)
{
ArcNode *p=G.vertices[v].firstarc;
while(p&&p->adjvex!=w)
{
p=p->nextarc;
}
if(p->nextarc) return p->nextarc->adjvex;
else return -1;
}
void DFS(ALGraph G,int v,Visit proc)
{
visited[v]=1;proc(v);
for(int w=FirstAdjVex(G,v);w>=0;w=NextAdjVex(G,v,w))
if(visited[w]==0) DFS(G,w,proc);
}
void DFSTraverse(ALGraph G,Visit proc)
{
for(int i=0;i<G.vexnum;i++)
visited[i]=0;
for(i=0;i<G.vexnum;i++)
{
if(visited[i]==0) DFS(G,i,proc);
}
}
int PrintTree(int n)
{
printf(" %d /n",n);
return OK;
}
#include "graph.h"
#include "stdio.h"
void main()
{
ALGraph lvrong;
CreateDG(&lvrong);
my_print(lvrong);
printf("DFSTraverse(ALGraph,proc)/n");
DFSTraverse(lvrong,&PrintTree);
}