采用邻接表存储结构,编写一个判别无向图中任意给定的两个顶点之间是否存在一条长度为k的简单路径的算法。 | 您所在的位置:网站首页 › 深度优先算法判断有向图回路 › 采用邻接表存储结构,编写一个判别无向图中任意给定的两个顶点之间是否存在一条长度为k的简单路径的算法。 |
问题描述:试基于图的深度优先搜索策略编写一程序,判别以邻接表存储的有向图中是否存在有顶点Vi到Vj顶点的路径(i!=j)。 输入:顶点个数,边数。顶点,边,要找的顶点i到j。 输出:若存在i到j路径,输出Exist the path,否则输出Not exist the path。 存储结构:邻接表存储结构。 算法基本思想:建立邻接表存储各顶点,边。然后深度优先搜索,用visited[i]作标志。 源程序: #include "stdio.h" #include "conio.h" #define MAX_VERTEX_NUM 30 typedef struct ArcNode{ int adjvex; struct ArcNode *nextarc; }ArcNode; typedef struct VNode{ int data; ArcNode *firstarc; }VNode,AdjList[MAX_VERTEX_NUM]; typedef struct{ AdjList vertices; int vexnum,arcnum; }ALGraph; creat_DG_ALGraph(ALGraph *G){ int i,j,k;ArcNode *p; p=NULL; printf("Please input: vexnum ,arcnum=:"); scanf("%d,%d",&G->vexnum,&G->arcnum); printf("Please input VNode:\n"); for(i=0;ivexnum;i++) {scanf("%d",&G->vertices[i].data); G->vertices[i].firstarc=NULL; } for(i=0;ivexnum;i++) printf("%d ",G->vertices[i].data); printf("\n"); for(k=0;karcnum;k++) {p=(ArcNode*)malloc(sizeof(ArcNode)); printf("please input edge : "); scanf("%d,%d", &i, &j); printf("\n"); p->adjvex = j; p->nextarc=G->vertices[i].firstarc; G->vertices[i].firstarc=p; } } int exist_path_DFS(ALGraph G,int i,int j){ ArcNode *p; int k,visited[MAX_VERTEX_NUM]; p=NULL; if(i==j) return 1; else {visited[i]=1; for(p=G.vertices[i].firstarc;p;p=p->nextarc) {k=p->adjvex; if(!visited[k]&&exist_path_DFS(G,k,j)); } } } main() {ALGraph *G; int i,j; G=NULL; creat_DG_ALGraph(G); printf("Please input i->j you want to find:\n"); scanf("%d,%d",&i,&j); if(exist_path_DFS(*G,i,j)) printf("Exist the path!"); else printf("Not exist the path"); getch(); } |
CopyRight 2018-2019 实验室设备网 版权所有 |