图的广度优先遍历和深度优先遍历Word文档下载推荐.docx
《图的广度优先遍历和深度优先遍历Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《图的广度优先遍历和深度优先遍历Word文档下载推荐.docx(9页珍藏版)》请在冰豆网上搜索。
}ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedefstruct
VertexTypevexs[MAX_VERTEX_NUM];
//极点向量
AdjMatrixarcs;
//邻接矩阵
intvexnum,arcnum;
//图的以后极点数和弧数.
Graphkindkind;
}MGraph;
typedefstructArcNode
intadjvex;
intweight;
structArcNode*nextarc;
}ArcNode;
typedefstructVNode
intdata;
ArcNode*firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
AdjListvertices;
intkind;
}ALGraph;
intLocateVex(MGraphG,VertexTypev1)
inti;
for(i=0;
i<
G.vexnum;
i++)
if(G.vexs[i]==v1)
returni;
return-1;
}
typedefstructNode
{
structNode*next;
}LinkQueueNode;
typedefstruct
LinkQueueNode*front;
LinkQueueNode*rear;
}LinkQueue;
intInitQueue(LinkQueue*Q)
Q->
front=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if(Q->
front!
=NULL)
Q->
rear=Q->
front;
front->
next=NULL;
return(True);
}
else
return(False);
intEnterQueue(LinkQueue*Q,intx)
LinkQueueNode*NewNode;
NewNode=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if(NewNode!
NewNode->
data=x;
rear->
next=NewNode;
rear=NewNode;
intDeleteQueue(LinkQueue*Q,int*x)
LinkQueueNode*p;
front==Q->
rear)
p=Q->
next;
next=p->
if(Q->
rear==p)
*x=p->
data;
free(p);
return(True);
intIsEmpty(LinkQueue*Q)
intvisited[MAX_VERTEX_NUM];
intCreatDN(MGraph&
G1,ALGraph&
G2)
//采纳数组暗示法,构造有向网G
intb;
ArcNode*p;
VertexTypev1,v2;
intw,j;
cout<
<
"
输入图的极点数及弧数"
endl;
cin>
>
G1.vexnum>
G1.arcnum;
G2.vexnum=G1.vexnum;
G2.arcnum=G1.arcnum;
输入极点向量"
for(inti=0;
G1.vexnum;
G1.vexs[i];
for(j=0;
j<
j++)
G1.arcs[i][j].adj=INFINITY;
G2.vexnum;
G2.vertices[i].data=i;
G2.vertices[i].firstarc=NULL;
输入边依附的两个极点及此边的权值"
for(intk=0;
k<
++k)//构造邻接矩阵
pleaseinput:
;
v1>
v2>
w;
i=LocateVex(G1,v1);
j=LocateVex(G1,v2);
G1.arcs[i][j].adj=w;
p=(ArcNode*)malloc(sizeof(ArcNode));
b=w;
p->
adjvex=j;
weight=b;
nextarc=G2.vertices[i].firstarc;
G2.vertices[i].firstarc=p;
return1;
voiddispMGraph(MGraphG)
图的邻接矩阵图是:
for(intj=0;
"
G.arcs[i][j].adj;
voidDepth1(MGraphg1,intvo)
intvj;
printf("
%c"
g1.vexs[vo]);
visited[vo]=True;
for(vj=0;
vj<
g1.vexnum;
vj++)
if((!
visited[vj])&
&
(!
g1.arcs[vo][vj].adj==0))
Depth1(g1,vj);
voidBreadth1(MGraphg1,intvo)
intvi,vj;
LinkQueueQ;
InitQueue(&
Q);
EnterQueue(&
Q,vo);
while(!
IsEmpty(&
Q))
DeleteQueue(&
Q,&
vi);
printf("
g1.vexs[vi]);
for(vj=0;
g1.arcs[vi][vj].adj==0))
{
visited[vj]=True;
EnterQueue(&
Q,vj);
}
voidTraverse1(MGraphg1)
intvi;
for(vi=0;
vi<
vi++)
visited[vi]=False;
\n深度优先遍历的结果:
\n"
);
if(!
visited[vi])
Depth1(g1,vi);
\n广度优先遍历的结果:
Breadth1(g1,vi);
voidchange1(MGraphG){
图的邻接矩阵转化为邻接表如下:
j++){
if(G.arcs[i][j].adj!
=0){
("
G.vexs[i]<
"
G.vexs[j]<
"
G.arcs[i][j].adj<
)"
}}
voidchange2(ALGraphG){
inta[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
inti,j,m;
图的邻接表转化为邻接矩阵如下:
p=G.vertices[i].firstarc;
while(p!
=NULL)
{m=p->
adjvex;
a[i][m]=p->
weight;
p=p->
nextarc;
}}
i++){
j++){
if(a[i][j]>
0);
elsea[i][j]=0;
a[i][j]<
voidmain()
inta;
MGraphG1;
ALGraphG2;
建立有向图"
CreatDN(G1,G2);
dispMGraph(G1);
Traverse1(G1);