基于深度优先搜索的两顶点路径存在与否的判断
描述
设计一个算法,试基于深度优先搜索判断以邻接表方式存储的有向图中是否存在由顶点vi到达顶点vj的路径。
输入
多组数据,每组m+3数据行。第一行有两个数字n和m,代表有n个顶点和m条边。第二行有n个字符,代表n个顶点的编号。第三行到第m+2行每行有两个字符h和k,代表边依附的两个顶点。第m+3行有两个字符vi和vj,代表需要判断的两个顶点。当n和m都等于0时,输入结束。
输出
每组数据输出一行。若存在路径输出“YES”,反之输出“NO”。
样例输入1
3 2
abc
ab
bc
ac
4 2
bcsw
bs
sw
cs
0 0
样例输出1
YES
NO
解答:深度优先搜索创建好的邻接表。
#include<stdio.h>
#include<stdlib.h>
#define maxn 300
typedef struct node
{
int data;
struct node *next;
} Node;
int flag;
int hash[maxn];
int visit[maxn];
Node *V[maxn];
void DFS(int s,int e)
{
visit[s]=1;
if(s == e)
{
flag=1;
return ;
}
Node *p=V[s]->next;
while(p)
{
if(!visit[p->data])
DFS(p->data,e);
p=p->next;
}
}
int main()
{
int n,m;
char x,y;
Node *p;
while(1)
{
scanf("%d %d",&n,&m);
if(n==0 && m==0)
break;
for(int i=0; i<maxn; i++)
hash[i]=0;
getchar();
for(int i=1; i<=n; i++)
{
scanf("%c",&x);
hash[x]=i;
V[i]=(Node *)malloc(sizeof(Node));
V[i]->data=i;
V[i]->next=NULL;
}
while(m--)
{
getchar();
scanf("%c %c",&x,&y);
p=(Node *)malloc(sizeof(Node));
p->data=hash[y];
p->next=V[hash[x]]->next;
V[hash[x]]->next=p;
p=(Node *)malloc(sizeof(Node));
p->data=hash[x];
p->next=V[hash[y]]->next;
V[hash[y]]->next=p;
}
for(int i=1; i<=n; i++)
visit[i]=0;
getchar();
scanf("%c %c",&x,&y);
flag=0;
DFS(hash[x],hash[y]);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}