Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

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

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

    • class Solution {
      public:
          int ladderLength(string start, string end, unordered_set<string> &dict) {
              if(start.size()!=end.size()) return 0;  
              if(start == end) return 2;  
                
              int min_value = 0;  
              unordered_set<string> unique;  
              unique.insert(start);  
                
              queue<string> que;  
              que.push(start);  
              int q1=1;  
              int q2=0;  
                
              while(q1>0) {  
                  string s = que.front();  
                  que.pop();  
                  --q1;  
                    
                  for(int i=0; i<s.size(); i++) {  
                      string temp = s;  
                      for(char c='a'; c<='z'; c++) {  
                          temp[i] = c;  
                          if(dict.find(temp)!=dict.end() && unique.find(temp)==dict.end()) {  
                              if(temp == end) {  
                                  return min_value+2;   
                              } else {  
                                  unique.insert(temp);  
                                  que.push(temp);  
                                  ++q2;  
                              }  
                          }  
                      }  
                  }  
                    
                  if(q1==0) {  
                      q1 = q2;  
                      q2 = 0;  
                      ++min_value;  
                  }  
              }  
              return 0;  
          }
      };

       

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

posted on 2014-12-03 17:49  code#swan  阅读(133)  评论(0)    收藏  举报

导航