Monday, November 24, 2014

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:
  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
Idea: Use BFS.
To do: make it more concise.
class Solution {
public:
  int ladderLength(string start, string end, unordered_set<string> &dict) {
   queue<string> curLevel;
   queue<string> nextLevel;
   string mid = start;
   bool find = false;
   string oStart = start;
   curLevel.push(start);
   int c = 1;
   while (!curLevel.empty() || !nextLevel.empty())
   {
    if (curLevel.empty())
    {
     curLevel.swap(nextLevel);
     c++;
    }
    start = curLevel.front();
    curLevel.pop();
    if (start == end)
    {
     find = true;
     break;
    }
    int n = start.size();
    for (int i = 0; i < n; i++)
    {
     for (int j = 0; j < 26; j++)
     {
      mid = start;
      if (start[i] != 'a' + j)
      {
       mid[i] = 'a' + j;
       if (dict.find(mid) != dict.end() || mid == end)  // To push the last element into the queue!
       {
        nextLevel.push(mid);
        if (dict.find(mid) != dict.end())
         dict.erase(mid); //
we need to get rid of the visited word to avoid circles.
       }
       else
       {
        continue;
       }
      }
     }
    }
   }
   if (find)
    return c;
   else
    return 0;
  }
};

No comments:

Post a Comment