路径搜索.docx
《路径搜索.docx》由会员分享,可在线阅读,更多相关《路径搜索.docx(7页珍藏版)》请在冰豆网上搜索。
![路径搜索.docx](https://file1.bdocx.com/fileroot1/2022-11/20/9a421f63-b5a4-4c81-aa32-62dc7dae4243/9a421f63-b5a4-4c81-aa32-62dc7dae42431.gif)
路径搜索
查找一个图中从结点i到结点j的所有简单路径。
用广度优先搜索和深度优先搜索分别实现。
constintmaxsize=12;
#include
usingnamespacestd;
structedgenode
{
intadjvex;
edgenode*next;
};
template
structvexnode
{
Tvertex;
edgenode*link;
};
template
structtreenode
{
Tver;
intparent;
};
template
classsequeue
{
public:
sequeue(){};
~sequeue(){};
voidsetnull();
voidenqueue(Tx);
Tdequeue();
intempty();
private:
Tdata[maxsize];
intfront,rear;
};
template
voidsequeue:
:
setnull()
{
front=rear=maxsize-1;
}
template
voidsequeue:
:
enqueue(Tx)
{
if((rear+1)%maxsize==front)
cout<<"error"<rear=(rear+1)%maxsize;
data[rear]=x;
}
template
Tsequeue:
:
dequeue()
{
if(front==rear)
cout<<"xiayi"<front=(front+1)%maxsize;
returndata[front];
}
template
intsequeue:
:
empty()
{
returnfront==rear?
1:
0;
}
template
classALGraph
{
public:
friendsequeue;
ALGraph(){};
voidALGraph1(intn,inte);
~ALGraph(){};
voidDFSL(inti,intj,intk);
voidBFSL(inti,intj);
voidchoose();
private:
vexnodega[maxsize];
intn,e;
intpath[maxsize],visited[maxsize];
};
template
voidALGraph:
:
ALGraph1(intvexnum,intedgenum)
{
inti,j,k;
edgenode*s;
n=vexnum;
e=edgenum;
cout<<"请输入结点:
"<for(i=0;i{
cin>>ga[i].vertex;
ga[i].link=0;
visited[i]=0;
}
cout<<"请输入各条边:
"<for(k=0;k{
cin>>i>>j;
s=newedgenode;
s->adjvex=j;
s->next=ga[i-1].link;
ga[i-1].link=s;
}
}
template
voidALGraph:
:
DFSL(inti,intj,intk)
{
edgenode*p;
intm;
path[k++]=i;
visited[i-1]=1;
p=ga[i-1].link;
if(path[k-1]==j)
{
for(m=0;mcout<";
cout<visited[j-1]=0;
k--;
}
while(p!
=0)
{
if(!
visited[p->adjvex-1])
DFSL(p->adjvex,j,k);
p=p->next;
}
visited[path[k]-1]=0;
k--;
}
template
voidALGraph:
:
BFSL(inti,intj)
{
intm,pa[maxsize];
for(intx=0;xvisited[x]=0;
edgenode*p;
treenodetree[maxsize];
sequeueQ;
Q.setnull();
Q.enqueue(i);
visited[i-1]=1;
while(!
Q.empty())
{
m=Q.dequeue();
tree[m-1].ver=m;
p=ga[m-1].link;
while(p)
{
if(!
visited[p->adjvex-1])
{
//visited[p->adjvex-1]=1;
Q.enqueue(p->adjvex);
tree[p->adjvex-1].parent=m-1;
tree[p->adjvex-1].ver=p->adjvex;
if(tree[p->adjvex-1].ver==j)
{
intk=0;
intl=j-1;
while(l>=0)
{
pa[k++]=tree[l].ver;
l=tree[l].parent;
}
for(--k;k>=0;k--)
cout<";
cout<//visited[j-1]=0;
}
}
p=p->next;
}
}
}
template
voidALGraph:
:
choose()
{
chara;
intk=0,i,j;
cout<<"请选择查找方式:
D:
(深度)、B:
(广度)!
"<cin>>a;
cout<<"请输入起点和终点:
"<cin>>i>>j;
switch(a)
{
case'D':
DFSL(i,j,k);choose();
case'B':
BFSL(i,j);choose();
}
}
voidmain()
{
ALGraphG;
intvexnum,edgenum;
cout<<"请输入结点数和边数:
"<cin>>vexnum>>edgenum;
G.ALGraph1(vexnum,edgenum);
G.choose();
}
运行结果示意图: