分别采用基于深度优先遍历和广度优先遍历算法判别以邻接表方式存储的有向图中是否存在由顶点v1到顶点vj的路径(i!=j),注意,算法中设计的图的基本操作必须在此存储结构上实现
#include <iostream>
#include<queue>
#define maxsize 10
typedef struct node{
int data;
struct node *next;
}node ,*pnode;
pnode buynode(int x)
{
pnode tmp=(pnode) malloc(sizeof (node));
tmp->data=x;
tmp->next= nullptr;
return tmp;
}
pnode * graph(int point)//结点数量
{
pnode * g=(pnode*) malloc(sizeof (pnode)*point);
for(int i=0;i<point;i++)
g[i]= buynode(i);
return g;
}
void insert(pnode* g,int p1,int p2)
{
pnode tmp=g[p1];
while(tmp->next&&tmp->next->data<p2) tmp=tmp->next;
pnode ne=tmp->next;
tmp->next= buynode(p2);
tmp->next->next=ne;
tmp=g[p2];
while(tmp->next&&tmp->next->data<p1) tmp=tmp->next;
ne=tmp->next;
tmp->next= buynode(p1);
tmp->next->next=ne;
}
void figure1(pnode* g)
{
insert(g,0,1);
insert(g,0,2);
insert(g,1,3);
insert(g,1,4);
}
void figure2(pnode* g)
{
insert(g,0,1);
insert(g,0,2);
insert(g,1,3);
insert(g,1,4);
}
void print(pnode *g,int point)
{
for(int i=0;i<point;i++)
{
pnode tmp=g[i];
while(tmp) {
printf("%3d",tmp->data);
tmp=tmp->next;
}
puts("");
}
}
bool bfs_way(pnode* g,int p1,int p2)
{
std::queue<pnode> record;
record.push(g[p1]);
int*visited=(int *) malloc(maxsize*sizeof (int));
for(int i=0;i<10;i++) visited[i]=0;
visited[p1]=1;
printf("the bfs path is:");
while(!record.empty())
{
pnode head=record.front();
record.pop();
printf("%2d->",head->data);
if(head->data==p2) {
puts("");
return true;
}
while(head->next)
{
if(!visited[head->next->data])//没有被访问过
{
visited[head->next->data]=1;
record.push(g[head->next->data]);
}
head=head->next;
}
}
puts("");
return false;
}
void _dfs_way(pnode* g,int* visited,int p1,int p2,bool &res)
{
printf("%2d->",g[p1]->data);
if(p1==p2) {
res= true;
return;
}
visited[p1]=1;
pnode tmp=g[p1];
if(tmp->next== nullptr) return;
while(tmp->next){
if(!visited[tmp->next->data])//下一个没有被访问过
{
// visited[tmp->next->data]= 1;
_dfs_way(g,visited,tmp->next->data,p2,res);
}
tmp=tmp->next;
}
}
bool dfs_way(pnode* g,int p1,int p2)
{
int * visited=(int*) malloc(sizeof (int)*maxsize);
for(int i=0;i<maxsize;i++) visited[i]=0;
bool res= false;
printf("the dfs path is:");
_dfs_way(g,visited,p1,p2,res);
puts("");
return res;
}
void exist(pnode* g,int p1,int p2)
{
if(bfs_way(g,p1,p2)){
printf("bfs:the way form point %d to %d is existed\n",p1,p2);
}else printf("bfs:the way form point %d to %d is not existed\n",p1,p2);
if(dfs_way(g,p1,p2)){
printf("dfs:the way form point %d to %d is existed\n",p1,p2);
}else printf("dfs:the way form point %d to %d is not existed\n",p1,p2);
}
int main() {
pnode* g1=graph(5);
figure1(g1);
print(g1,5);
exist(g1,3,4);
pnode* g2=graph(6);//图2的点5是孤立的
figure2(g2);
print(g2,6);
exist(g2,3,5);
return 0;
}
测试的分别是两棵树