每日一题Day69

基于深度优先搜索的两顶点路径存在与否的判断

描述

设计一个算法,试基于深度优先搜索判断以邻接表方式存储的有向图中是否存在由顶点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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值