#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAX_VERTEX_NUM 50
typedef char VertexType[3];
typedef struct edgenode
{
int adjvex;
int value;
struct edgenode *next;
}ArcNode;
typedef struct vexnode{
VertexType data;
ArcNode *firstarc;
}VHeadNode;
typedef struct
{
int Vertex_Num,Edge_Num;
VHeadNode adjlist[MAX_VERTEX_NUM];
}AdjList;
int visited[MAX_VERTEX_NUM];
int Create_Adj_List_undirected_graph(AdjList *&G){
int i,b,t,w;
ArcNode *p;
G=(AdjList *)malloc(sizeof(AdjList));
printf(“顶点数,边数\n”);
scanf(“%d%d”,&G->Vertex_Num,&G->Edge_Num);
for(i=0;i<G->Vertex_Num;i++)
{
printf(“序号为%d的顶点信息:”,i);
scanf(“%s”,&G->adjlist[i].data);
G->adjlist[i].firstarc=NULL;
}
for(i=0;i<G->Edge_Num;i++)
{
printf(“起点号 终点号 权值\n”);
scanf(“%d%d%d”,&b,&t,&w);
if(b<G->Vertex_Num&&t<G->Vertex_Num&&w>0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->value=w;
p->adjvex=t;
p->next=G->adjlist[b].firstarc;
G->adjlist[b].firstarc=p;
}
else
{
printf(“输入有误!!\n”);
return 0;
}
}
return 1;
}
void Disp_Adj_List(AdjList *G)
{
int i;
ArcNode *p;
printf(“图的邻接表表示如下:\n”);
for(i=0;i<G->Vertex_Num;i++)
{
printf(“[%d,%3s]=>”,i,G->adjlist[i].data);
p=G->adjlist[i].firstarc;
while(p!=NULL)
{
printf(“(%d,%d)->”,p->adjvex,p->value);
p=p->next;
}
printf(“^\n”);
}
}
//深度优先算法
void DFS(AdjList *g,int vi)
{
ArcNode *p;
printf(“%d”,vi);
visited[vi]=1;
p=g->adjlist[vi].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
DFS(g,p->adjvex);
p=p->next;
}
}
void main()
{
int i;
AdjList *G;
Create_Adj_List_undirected_graph(G);
Disp_Adj_List(G);
memset(visited,sizeof(visited),0);
printf(“从顶点0深度优先遍历\n”);
printf(“递归算法:\n”);
DFS(G,0);
printf(“\n”);
}