/*
Copyright (c)2017,烟台大学计算机与控制工程学院
All rights reserved.
文件名称:第十一周项目4 - 利用遍历思想求解图问题.cpp
作 者:孙仁圆
完成日期:2017年12月27日
版 本 号:v1.0
问题描述: 假设图G采用邻接表存储,分别设计实现以下要求的算法,要求用区别于示例中的图进行多次测试,通过观察输出值,掌握相关问题的处理方法。
(1)设计一个算法,判断顶点u到v是否有简单路径
输入描述:若干测试数据。
程序输出:相应的数据输出。
*/
#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV]; //定义存放节点的访问标志的全局数组
void ExistPath(ALGraph *G,int u,int v, bool &has)
{
int w;
ArcNode *p;
visited[u]=1;
if(u==v)
{
has=true;
return;
}
p=G->adjlist[u].firstarc;
while (p!=NULL)
{
w=p->adjvex;
if (visited[w]==0)
ExistPath(G,w,v,has);
p=p->nextarc;
}
}
void HasPath(ALGraph *G,int u,int v)
{
int i;
bool flag = false;
for (i=0; i<G->n; i++)
visited[i]=0; //访问标志数组初始化
ExistPath(G,u,v,flag);
printf(" 从 %d 到 %d ", u, v);
if(flag)
printf("有简单路径\n");
else
printf("无简单路径\n");
}
int main()
{
ALGraph *G;
int A[5][5]=
{
{0,0,0,0,0},
{0,0,1,0,0},
{0,0,0,1,1},
{0,0,0,0,0},
{1,0,0,1,0},
}; //请画出对应的有向图
ArrayToList(A[0], 5, G);
HasPath(G, 1, 0);
HasPath(G, 4, 1);
return 0;
}