Monday, May 20, 2013

Leetcode: Word Ladder in C++



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
  1. Each intermediate word must exist in the dictionary
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
return its length 5.

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

For example,
Given:
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
Note:

Solution: BFS
int ladderLength(string start, string end, unordered_set<string> &dict) {
        if(start.size()!=end.size())
            return 0;
        queue<string> cur;
        queue<string> next;
        cur.push(start);
        int distance =1;
        while(!cur.empty()&&dict.size()>0)
        {
            while(!cur.empty())
            {
                string tmp = cur.front();
                cur.pop();
                for(int i=0;i<tmp.size();i++)
                {
                    char k = tmp[i];
                    for(char m='a';m<='z';m++)
                    {
                        if(m==k)
                        continue;
                        tmp[i] = m;
                        if(tmp == end)
                        return distance+1;
                        if(dict.count(tmp)>0)
                        {
                            next.push(tmp);
                            dict.erase(tmp);
                        }
                        tmp[i] = k;
                    }
                }
            }
            swap(cur, next);
            distance++;
        }
        return 0;
    }

No comments:

Post a Comment