Word Ladder

LeetCode – Word Ladder

 

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that only one letter can be changed at a time and each intermediate word must exist in the dictionary. For example, given:

start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

 1 class Solution{
 2 public:
 3     int ladderlength(string start,string end,unordered_set<string> &dict){
 4         if(start == end){
 5             return 0;
 6         }
 7         unordered_map<string,int> len;
 8         len[start] = 1;
 9         queue<string> q;
10         for(q.push(start);!q.empty();q.pop()){
11             string word = q.front();
12             int step = len[start] + 1;
13             for(int i = 0;i<word.length();i++){
14                 for(char ch = 'a';ch <= 'z';++ch){
15                     if(word[i] != ch){
16                         char temp = word[i];
17                         word[i] = ch;
18                         if((dict.find(word)!=dict.end())&&(len.find(word)==len.end())){
19                             if(start == end){
20                                 return step;
21                             }
22                             q.push(word);
23                             len[word] = step;
24                          }
25                         word[i] = temp;
26                     }
27                 }
28             }
29         }
30         return 0;
31     }
32 }
原文地址:https://www.cnblogs.com/Dillonn/p/4546105.html