单词序列

来源:互联网 发布:数据库join 笛卡尔 编辑:程序博客网 时间:2024/06/16 11:52
总时间限制: 1000ms 内存限制: 1024kB
描述
给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:


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


广搜题,没什么坑的,按部就班就行了


#include <iostream>    #include<cstring>#include<string>#include<queue>using namespace std;string dic[35];int vis[35];int cnt = 0;string beg, goal, tmp;bool flag = false;int len;//size of each wordint check(string s){if (s == goal){return cnt;}for (int i = 0; i < cnt; ++i){if (dic[i] == s){return i;}}return -1;}struct node{string s;int step;node(string ss,int st):s(ss),step(st){}node(){}};void bfs(node b){queue<node> q;q.push(b);while (!q.empty()){node head = q.front();if (head.s == goal){flag = true;cout << head.step+1;return;}else{for (int i = 0; i < len; ++i){for (int j = 0; j < 26; ++j){string tmps = head.s;tmps[i] = 'a' + j;int x = check(tmps);if (x == -1){continue;}else{if (vis[x] == 0){vis[x] = 1;q.push(node(tmps, head.step + 1));}}}}q.pop();}}}int main(){cin >> beg;cin >> goal;while (cin >> tmp){dic[cnt] = tmp;++cnt;}len = beg.size();bfs(node(beg, 0));if (!flag){cout << 0;}return 0;}