假设图用邻接表表示,设计一个算法,输出从顶点vi到顶点vj的所有简单路径
#include <iostream>]
#include <string.h>
#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,1,2);
insert(g,2,3);
insert(g,3,4);
insert(g,4,0);
insert(g,0,2);
insert(g,0,3);
}
void print(pnode *g,int point)
{
for(int i=0;i<5;i++)
{
pnode tmp=g[i];
while(tmp) {
printf("%3d",tmp->data);
tmp=tmp->next;
}
puts("");
}
}
void _dfs(pnode *g,int p1,int p2,int*visited,int*path,int &pointer)
{
visited[p1]=1;
path[++pointer]=p1;
if(p1==p2){
for(int i=0;i<=pointer;i++) printf("%2d->",path[i]);
puts("");
return;
}
pnode tmp=g[p1];
while(tmp->next){
if(!visited[tmp->next->data])//没有访问过
{
_dfs(g,tmp->next->data,p2,visited,path,pointer);
visited[path[pointer]]=0;
pointer--;
}
tmp=tmp->next;
}
}
void dfs(pnode* g,int p1,int p2)
{
int *visited=(int*) malloc(sizeof (int)*maxsize);
int *path=(int*) malloc(sizeof (int )*maxsize);
int pointer=-1;
for(int i=0;i<maxsize;i++) visited[i]=0,path[i]=0;
printf("the paths are:\n");
_dfs(g,p1,p2,visited,path,pointer);
}
int main() {
pnode* g1=graph(5);
figure1(g1);
print(g1,5);
dfs(g1,0,3);
return 0;
}
测试用的树如下
测试从0到3的全部路径