poj-单词序列

参考来源:http://www.cnblogs.com/huashanqingzhu/category/852024.html

描述

给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:

1、每次只能改变一个字母

2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中

例如:

开始单词为:hit

结束单词为:cog

词典为:[hot,dot,dog,lot,log,mot]

那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,

所以返回的结果是序列的长度5;

注意:

1、如果不能找到这种变换,则输出0;

2、词典中所有单词长度一样;

3、所有的单词都由小写字母构成;

4、开始单词和结束单词可以不在词典中。

输入

共两行,第一行为开始单词和结束单词(两个单词不同),以空格分开。第二行为若干的单词(各不相同),以空格分隔开来,表示词典。单词长度不超过5,单词个数不超过30。输出输出转换序列的长度。

样例输入

hit cog
hot dot dog lot log
样例输出
5

解题思路:

bfs的运用,注意字符串的输入部分的格式,当cin.get()=='\n'时,while(cin>>s)结束输入

# include<stdio.h>
# include<queue>
# include<string>
# include<iostream>
using namespace std;

struct E
{
	string s;
	int cnt;
}m[1000];

queue<int >  Q;
int mark[1000];
int vis=0;

int judge(string a,string b)
{
	int count=0;
	for(int i=0;i<a.size();i++)
	{
		if(a[i]!=b[i])
		{
			count++;
			if(count>1)
				break;
		}
	}
	return count;
}

int main()
{
	string s,t,total;
	char tmp[1000];
	int index;
	int i,j;
	cin>>s>>t;
    m[1].s=s;
	m[1].cnt=0;
   
	index=2;
	while(cin>>m[index].s)
	{
		index++;
		if(cin.get()=='\n')
			break;
	}
    
	m[index].s=t;
    m[index].cnt=0;

	Q.push(1);//初始点
	while(Q.empty()==false)
	{
		i=Q.front();
		Q.pop();
		
		if(m[i].s==t)
		{
			printf("%d\n",m[i].cnt+1);
			vis=1;
			break;
		}
		
		else
		{
			for(j=1;j<=index;j++)
			{
				if(judge(m[i].s,m[j].s)==1&&mark[j]==0)
				{
					Q.push(j);
					mark[j]=1;
					m[j].cnt=m[i].cnt+1;
				}
			}
		}
	}
	
	if(vis==0)
        printf("0\n");
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhuixun_/article/details/80251485