Word Ladder

来源:互联网 发布:山东男人啪的表现知乎 编辑:程序博客网 时间:2024/06/12 02:12
-----QUESTION-----

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:

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

-----SOLUTION-----

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        int wordLen = start.length();        int distance = 1;        string current;        queue<string> queue_to_push; //prepared for next loop        queue<string> queue_to_pop; //string to deal in this loop              queue_to_pop.push(start);        while(!queue_to_pop.empty())        {            current = queue_to_pop.front();            queue_to_pop.pop();                     for (int i = 0; i < wordLen; i++)              for (int j = 'a'; j <= 'z'; j++)              {                  if (j == current[i]) //skip the current character                      continue;                  char temp = current[i];                  current[i] = j;                  if(current==end)                {                    return distance+1;                }                if (dict.count(current) > 0) //exist such a word in the dict                  {                      dict.erase(current); //delete such a word                      queue_to_push.push(current);                }                  current[i] = temp;  //restore the string            }            if(queue_to_pop.empty())            {                swap(queue_to_push, queue_to_pop);                distance++;            }        }        return 0; //fail to find    }};

0 0
原创粉丝点击