1. 程式人生 > >18.06.02 POJ4128:單詞序列 15年程設期末06

18.06.02 POJ4128:單詞序列 15年程設期末06

lse flag AC visit 小寫 UC display memory b2b

描述

給出兩個單詞(開始單詞和結束單詞)以及一個詞典。找出從開始單詞轉換到結束單詞,所需要的最短轉換序列。轉換的規則如下:

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 <iostream>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <cstdio>
 5 #include <stdlib.h>
 6
#include <string> 7 #include <memory> 8 #include <queue> 9 10 using namespace std; 11 12 struct word { 13 char words[7]; 14 int step; 15 word() { step = 0; } 16 }; 17 word diction[31]; 18 word start, endw; 19 int num = 1; 20 bool visited[31]; 21 22 queue<word>all;
23 24 int cmp(word&a, word&b) { 25 int count = 0; 26 int l = strlen(a.words); 27 for (int i = 0; i < l; i++) 28 if (a.words[i] != b.words[i]) 29 count++; 30 return count; 31 } 32 33 void bfs() { 34 bool flag = false; 35 while (!all.empty()) { 36 word now = all.front(); 37 all.pop(); 38 for (int i = 1; i <= num; i++) { 39 if (visited[i] != 1 && cmp(now, diction[i]) == 1) { 40 visited[i] = 1; 41 diction[i].step = now.step + 1; 42 if (cmp(diction[i], endw) == 1) { 43 flag = true; 44 printf("%d\n", diction[i].step + 2); 45 return; 46 } 47 all.push(diction[i]); 48 } 49 } 50 } 51 if (flag == false) 52 printf("0\n"); 53 } 54 55 int main() 56 { 57 cin >> start.words >> endw.words; 58 while (cin >> diction[num].words) 59 num++; 60 if (cmp(start, endw) == 1) 61 { 62 printf("2\n"); 63 return 0; 64 } 65 all.push(start); 66 bfs(); 67 return 0; 68 }
View Code

普通的廣搜 註意開始單詞和結束單詞只差一個字母的情況

18.06.02 POJ4128:單詞序列 15年程設期末06