(1)DFS
图采用邻接表的结构,头文件algraph.h如下:
#defineMAX_VERTEX_NUM20
typedefintInfoType;
typedefcharVertexType;

typedefenum...{DG,DN,UDG,UDN}GraphKind;

typedefstructArcNode...{
intadjvex;
structArcNode*next;
InfoTypeinfo;
}ArcNode;

typedefstructVNode...{
VertexTypedata;
ArcNode*firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];

typedefstruct...{
AdjListvertex;
intvexnum,arcnum;
GraphKindkind;
}algraph;
boolflag[MAX_VERTEX_NUM];
DFS的递归算法如下:
#include"algraph.h"
#include"stdio.h"
#include"stdlib.h"

voidcreateDN(algraph&g)...{}
voidcreateUDN(algraph&g)...{}
voidcreateUDG(algraph&g)...{}
//gettheverticename'sindex
intlocate(algraphg,charname)...{
for(inti=0;i<g.vexnum;i++)...{
if(name==g.vertex[i].data)...{
returni;
}
}
return-1;
}

voidcreateDG(algraph&g)...{
printf("inputthenumberofvertexandarcs: ");
scanf("%d%d",&g.vexnum,&g.arcnum);
fflush(stdin);
inti=0,j=0,k=0;
printf("inputthenameofvertex: ");
//initthevertexnames
for(i=0;i<g.vexnum;i++)...{
scanf("%c",&g.vertex[i].data);
fflush(stdin);
g.vertex[i].firstarc=NULL;
}
//constructthegraph'sadjacentlinklist
charv1,v2;
intw;
ArcNode*p;
printf("inputthe%darcsv1v2andweight: ",g.arcnum);
for(k=0;k<g.arcnum;k++)...{
scanf("%c%c%d",&v1,&v2,&w);
fflush(stdin);
i=locate(g,v1);
j=locate(g,v2);
//newalinknode
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=j;
p->info=w;
p->next=NULL;
//insertthenewnodetotheheadoflist
if(!g.vertex[i].firstarc)...{
g.vertex[i].firstarc=p;
}else...{
p->next=g.vertex[i].firstarc;
g.vertex[i].firstarc=p;
}
}
}
//printthegraph
voidprintGraph(algraphg)...{
for(inti=0;i<g.vexnum;i++)...{
printf("theedgesofvretice%c: ",g.vertex[i].data);
ArcNode*p=g.vertex[i].firstarc;
while(p)...{
printf("%c(%d) ",g.vertex[p->adjvex].data,p->info);
p=p->next;
}
printf(" ");
}
}

voidcreateGragh(algraph&g)...{
printf("pleaseinputthetypeofgraph: ");
scanf("%d",&g.kind);

switch(g.kind)...{
caseDG:
createDG(g);
printGraph(g);
break;
caseDN:
createDN(g);
break;
caseUDG:
createUDG(g);
break;
caseUDN:
createUDN(g);
break;
}
}

voidvisit(algraphg,intv)...{
printf("%c",g.vertex[v].data);
}
//dfsthegraph
voiddfs(algraphg,inti,void(*f)(algraph,int))...{
flag[i]=1;
f(g,i);
ArcNode*p=g.vertex[i].firstarc;
while(p)...{
intadj=p->adjvex;
if(!flag[adj])...{
dfs(g,adj,f);
}
p=p->next;
}
}

voiddfsTraval(algraphg,void(*f)(algraph,int))...{
for(inti=0;i<g.vexnum;i++)...{
flag[i]=0;
}

for(i=0;i<g.vexnum;i++)...{
if(!flag[i])...{
dfs(g,i,f);
}
}
}

voidmain()...{
algraphg;
createGragh(g);
void(*f)(algraph,int);
f=visit;
dfsTraval(g,f);
}
(2)BFS
使用队列对图节点进行遍历。
程序略。
关于图的遍历算法的复杂度:
1. 图的DFS:使用的是邻接表的结构时,算法的复杂度是O(n + e);使用的是邻接矩阵的结构时,算法的复杂度是O(n2)。
2. 遍历图的过程实质是通过边或者弧找邻接点的过程,所以BDS和DFS的算法的复杂度相同,二者的区别在于对顶点的访问顺序不同。
本文详细介绍了图的深度优先搜索(DFS)和广度优先搜索(BFS)两种基本遍历方法,并提供了具体的算法实现。针对DFS算法,文章给出了递归实现过程及其复杂度分析。
403

被折叠的 条评论
为什么被折叠?



