Description:
给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:
1、每次只能改变一个字母
2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中
例如:
开始单词为:hit
结束单词为:cog
词典为:[hot,dot,dog,lot,log,mot]
那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,
所以返回的结果是序列的长度5;
注意:
1、如果不能找到这种变换,则输出0;
2、词典中所有单词长度一样;
3、所有的单词都由小写字母构成;
4、开始单词和结束单词可以不在词典中。
解题思路:
算法标签:BFS
对每个与上一个字符串是否有一个字符不相同且未被访问过就入队,最先找到结束单词就是最短序列。
注意要用 vis 数组保存是否已经入队,否则会做重复的搜索而且会超内存,注意 vis 的初始化(记得定义全局变量不是初始化false,但是我的wrong了)
代码:
// TSWorld
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
#define rep(i,l,r) for(int i = l; i <= r;i++)
#define ll long long
const int N = 40;
string start,en;
string dic[N];
int times;
struct Node {
string word;
int step;
};
queue<Node>q;
bool vis[N];
bool issamed(string src,string des) {
int same = 0;
for(int i = 0;i < src.length();i++) {
if(src[i] != des[i])
same++;
if(same > 1)
break;
}
if(same == 1){
//cout<<src<<" "<<des<<endl;
return true;
}
else
return false;
}
void Bfs() {
struct Node head;
struct Node temp;
bool isresult = false;
memset(vis,false,sizeof(vis));
while(!q.empty()) {
head = q.front();
q.pop();
if(head.word == en){
isresult = true;
break;
}
for(int i = 1;i <= times;i++) {
if(issamed(head.word,dic[i]) && !vis[i]) {
temp.word = dic[i];
temp.step = head.step+1;
vis[i] = true;
q.push(temp);
}
}
}
if(isresult)
cout<<head.step;
else
cout<<0;
}
int main()
{
struct Node head;
cin>>start>>en;
times = 1;
while(cin>>dic[times]){
times++;
}
dic[times] = en;
head.word = start;
head.step = 1;
q.push(head);
Bfs();
return 0;
}