图的优先遍历算法(C语言版)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#define MAX_VERTEX_NUM 20
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
char data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum,arcnum;
}ALGraph;
void CreateAL(ALGraph *G);
int LocateVex(ALGraph G,char u);
void DFSTraverse(ALGraph G,void (*Visit)(ALGraph G,int v)); void PrintElem(ALGraph G,int v);
void DFS(ALGraph G,int v);
int FirstAdjVex(ALGraph G,int v);
int NextAdjVex(ALGraph G,int v,int w);
int visited[MAX_VERTEX_NUM];
void (*VisitFunc)(ALGraph G,int v);
int main(){
ALGraph G;
CreateAL(&G);
printf("The Graph is:\n");
DFSTraverse(G,PrintElem);
getch();
}
void CreateAL(ALGraph *T){
int i,j,m;
ArcNode *p,*s;
char ch[100];
printf("Please input the vexnum and arcnumm:\n");
scanf("%d%d",&(T->vexnum),&(T->arcnum));
printf("Please input the vertexs:\n");
for(i=0;i<(T->vexnum);++i){
scanf(" %c",&(T->vertices[i].data));
T->vertices[i].firstarc=NULL;
}
for(i=0;i<(T->vexnum);++i){
m=0;
printf("Please input the adjacents of %c\n",T->vertices[i].data);
scanf(" %s",&ch);
j=LocateVex(*T,ch[0]);
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->nextarc=NULL;
T->vertices[i].firstarc=p;
while(ch[++m]!='\0'){
j=LocateVex(*T,ch[m]);
s=(ArcNode *)malloc(sizeof(ArcNode));
s->adjvex=j;
s->nextarc=NULL;
p->nextarc=s;
p=s;
}
}
}
int LocateVex(ALGraph G,char u){
int j;
int i=sizeof(G.vertices)/sizeof(VNode);
for(j=0;j
if(u==G.vertices[j].data)
return j;
}
printf("Can not find the vertex! Please press any key to exit\n");
getchar();
getchar();
exit(ERROR);
}
void DFSTraverse(ALGraph G,void (*Visit)(ALGraph G,int v)){ int v;
VisitFunc=Visit;
for(v=0;v visited[v]=FALSE; for(v=0;v if(!visited[v]) DFS(G,v); } void DFS(ALGraph G,int v){ int w; visited[v]=TRUE; VisitFunc(G,v); for(w=FirstAdjVex(G,v);w>=0;w=NextAdjVex(G,v,w)) if(!visited[w]) DFS(G,w); } void PrintElem(ALGraph G,int v){ printf(" %3c",G.vertices[v].data); } int FirstAdjVex(ALGraph G,int v){ ArcNode *p=G.vertices[v].firstarc; return p->adjvex; } int NextAdjVex(ALGraph G,int v,int w){ ArcNode *p,*s; for(p=G.vertices[v].firstarc;p!=NULL;p=p->nextarc){ if(((p->adjvex)==w)&&(p->nextarc)){ s=p->nextarc; return s->adjvex; } } return ERROR; }