4128:单词序列(bfs)

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

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

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 string start,goal,temp;
 4 string a[30];
 5 int visit[30];
 6 struct Node {
 7     string s;
 8     int step;
 9     Node(string ss,int st):s(ss),step(st) {}
10 };
11 queue <Node> q;
12 
13 bool fun(string a,string b) {//比较两个字符串是否只相差一位 
14     int len=a.length();
15     int sum=0;
16     for(int i=0; i<len; i++) {
17         if(a[i]==b[i])sum++;
18     }
19     if(sum==len-1)return true;
20     else return false;
21 }
22 int main() {
23     cin>>start>>goal;
24     int n=0;
25     while(cin>>temp) {
26         a[n]=temp;
27         n++;
28     }
29     memset(visit,0,sizeof(visit));
30     while(!q.empty())q.pop();
31     q.push(Node(start,2));//初始就是2,因为输出的是整个路程,包括start和goal
32     while(!q.empty()) {
33         Node p=q.front();
34         q.pop();
35         if(fun(p.s,goal)) {
36             cout<<p.step<<endl;
37             return 0;
38         } else {
39             for(int i=0; i<n; i++) {
40                 if(!visit[i]&&fun(p.s,a[i])) {
41                     visit[i]=1;
42                     q.push(Node(a[i],p.step+1));
43                 }
44             }
45         }
46     }
47     cout<<0<<endl;//一定不要漏掉本行,wa了N次才发现
48     return 0;
49 }

 

posted @ 2020-04-03 22:01  瓜瓜爱呱呱  阅读(589)  评论(0编辑  收藏  举报