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.
struct Node
{
    string word;
    int path;
};

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dictout) 
    {
        if(start==end) return 1;
        
        int len=start.length();
        dictout.insert(start);
        dictout.insert(end);
        
        vector<Node*> path;
        
        Node* newnode=new Node();
        newnode->word=start;newnode->path=1;
        path.push_back(newnode);
        
        unordered_set<string> dictin;
        dictin.insert(start);
        dictout.erase(dictout.find(start));
        
        int index=0;
        while(index<path.size())
        {
            if(path[index]->word==end) return path[index]->path;
            //generate next
            string news=path[index]->word;
            for(int i=0;i<len;i++)
                for(int k=0;k<26;k++)
                    if(path[index]->word[i]!=k+'a')
                    {
                        news[i]=k+'a';
                        unordered_set<string>::const_iterator findout=dictout.find(news);
                        if(findout!=dictout.end() && dictin.find(news)==dictin.end())
                        {
                            newnode=new Node();
                            newnode->path=path[index]->path+1;
                            newnode->word=news;
                            path.push_back(newnode);
                            
                            dictin.insert(news);
                            dictout.erase(findout);
                        }
                        news[i]=path[index]->word[i];
                    }
            
            delete path[index];
            index++;
        }
        return 0;
    }
};

 

posted @ 2014-05-30 01:20  erictanghu  阅读(109)  评论(0编辑  收藏  举报