#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
#define true 0
#define false 1
int visited[MAX_VERTEX_NUM];
//typedef VertexType int;
typedef enum {DG,DN,AG,AN} GraphKind;
typedef struct ArcNode
{ //边(弧)结点的类型定义
int adjvex; //边(弧)的另一顶点的在数组中的位置
struct ArcNode *nextarc; //指向下一条边(弧)结点的指针
}ArcNode;
typedef struct Vnode
{ //顶点结点和数组的类型定义
int data; //顶点信息
ArcNode * finrstarc; //指向关联该顶点的边(弧)链表
}Vnode, AjList[MAX_VERTEX_NUM];
typedef struct
{
Vnode vertices[MAX_VERTEX_NUM];//AjList vertices
int vexnum, arcnum; //图的当前顶点数和弧数
GraphKind kind; //图的种类标志
}ALGraph;
void create(ALGraph &g)
{
int n,i,j,sum=0,count,t;
int x,k;
ArcNode *p;
printf("请输入图的顶点数目:");
scanf("%d",&n);
printf("请输入%d个顶点的编号,空格分隔:",n);
for (i=0;i<n;i++)
{
scanf("%d",&g.vertices[i].data);
g.vertices[i].finrstarc=NULL;
}
printf("请按照顶点输入顺序,依次输入和该点有边相连的顶点信息:\n");
for (i=0;i<n;i++)
{
printf("输入与顶点编号%d有边相连的条数:",g.vertices[i].data);
scanf("%d",&count);
sum=sum+count;
printf("再依次输入与顶点编号%d有边相连的顶点编号,中间用空格分隔:",g.vertices[i].data);
for (j=0;j<count;j++)
{
scanf("%d",&x);
//求出顶点对应的下标值
for (t=0;t<n;t++)
if (g.vertices[t].data==x)
{
k=t;
break;
}
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=k;
p->nextarc=g.vertices[i].finrstarc;
g.vertices[i].finrstarc=p;
}
}
g.kind=AG;
g.vexnum=n;
g.arcnum=sum/2;
}
ArcNode *p;
//图深度优先遍历函数定义
void DepthFirstSearch(ALGraph &g,int i)//参数i表示顶点的下标
{
visited[i]=1;
printf("%d ",g.vertices[i].data);
p=g.vertices[i].finrstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
DepthFirstSearch(g,p->adjvex);
p=p->nextarc;
}
}
void DFS(ALGraph &g)
{
int i;
for(i=0;i<g.vexnum;i++)
{
visited[i]=0;
}
for(i=0;i<5;i++)
{
if(visited[i]==0)
DepthFirstSearch(g,i);
}
}
//图广度优先遍历函数定义
//void BreadthFirstSearch(ALGraph g,int i)//参数i表示顶点的下标
void main()
{
int i,j,n;
ArcNode *p;
ALGraph g;
create(g);
printf("图的邻接表结构如下,以下出现的数字均为每个顶点的编号,而非下标值:\n");
for (i=0;i<g.vexnum;i++)
{
printf("%d--->",g.vertices[i].data);
p=g.vertices[i].finrstarc;
while (p!=NULL)
{
j=p->adjvex;
printf("%d ",g.vertices[j].data);
p=p->nextarc;
}
printf("\n");
}
printf("该图有%d个顶点,有%d条边。\n",g.vexnum,g.arcnum);
i=0;
printf("图的深度优先遍历结果:");
DFS(g);//图深度优先遍历函数调用
}