描述
给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:
1、每次只能改变一个字母
2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中
例如:
开始单词为:hit
结束单词为:cog
词典为:[hot,dot,dog,lot,log,mot]
那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,
所以返回的结果是序列的长度5;
注意:
1、如果不能找到这种变换,则输出0;
2、词典中所有单词长度一样;
3、所有的单词都由小写字母构成;
4、开始单词和结束单词可以不在词典中。
输入
输入数据共两行,第一行为开始单词和结束单词(两个单词不同),以空格分开。第二行为若干的单词(各不相同),以空格分隔开来,表示词典。单词长度不超过5,单词个数不超过30。
输出
输出转换序列的长度。
来源:中国大学MOOC程序设计与算法(二)期末考试(2018年秋季)
样例输入
hit cog
hot dot dog lot log
样例输出
5
使用queue和map,BFS。
思路
- 需要封装函数判断两个单词之间是否满足变换要求
- 开始单词、结束单词及字典单词统归为遍历目标,以开始单词为根,最底层出现结束单词则找到变换序列。
- 如果序列最短,则该序列单词不与同深度及以上的节点重复,可用对应key值记录序列长度;否则即不为最短序列(路径重复,则长度增加)。
- 如果最底层节点仍未出现结束单词,输出“0”。
#include <stdio.h> //所有头文件及宏定义为个人爱好
#include <stdlib.h>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#define maxf 31
using namespace std;
int judge(string a, string b) //判断两个单词相差字母个数
{
int leng = a.size(),flag=0;
for (int i = 0; i < leng; i++)
if (a[i] != b[i])flag++;
return flag;
}
int main()
{
int cnt = 0, maxw = maxf;
string dictionary[maxf];
map<string, int>visit;
string end;
cin >> dictionary[cnt++] >> end; //结束单词作为判断标准,单独记录
dictionary[cnt++] = end;
while (cin >> dictionary[cnt++]) {} //输入字典单词
queue<int>s; //以单词的输入顺序为下标,下标唯一,可作为标识(下标大小不影响排序)
int scnt;
s.push(0); //以开始单词为根向下搜索
visit[dictionary[0]] = 1; //记录到该节点层为止的序列长度
while (!s.empty()) //判断是否搜索了所有单词(与下文获取节点下标时使用的pop()结合实现)
{
scnt = s.front();
s.pop();
if (dictionary[scnt] == end) //该层该节点实现变换,输出最短序列长度
{
cout << visit[dictionary[scnt]] << endl;
return 0;
}
else
{
for (int i = 1; i < cnt; i++) //遍历
//(上文所述下标大小不影响排序,因为即使结束单词先被比较,不符合条件则不进入搜索二叉树)
{
if (judge(dictionary[i], dictionary[scnt]) == 1 && !visit[dictionary[i]])
//满足变换条件&&最短序列不出现同层及以上的节点
{
visit[dictionary[i]] =visit[ dictionary[scnt]] + 1; //序列长度记录
s.push(i);
}
}
}
}
cout << 0 << endl; //完全搜索所有单词,未能找到变换为结束单词的序列
return 0;
}