`
gaofen100
  • 浏览: 1189655 次
文章分类
社区版块
存档分类
最新评论

数据结构 图 图的遍历

 
阅读更多

(1)DFS

图采用邻接表的结构,头文件algraph.h如下:

#defineMAX_VERTEX_NUM20

typedef
intInfoType;
typedef
charVertexType;

typedef
enum...{DG,DN,UDG,UDN}GraphKind;

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

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

typedef
struct...{
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:使用的是邻接表的结构时,算法的复杂度是On + e);使用的是邻接矩阵的结构时,算法的复杂度是On2)。

2. 遍历图的过程实质是通过边或者弧找邻接点的过程,所以BDSDFS的算法的复杂度相同,二者的区别在于对顶点的访问顺序不同。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics