图 的深度遍历,创建。老师的实验,顺便发个贴!

 #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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值