[LeetCode] 把一个单词变形成为另一个单词,每次变形只改变一个单词 word ladder

给定两个相等长度的单词,写一个算法,把一个单词变形成为另一个单词,每次变形只改变一个单词。此过程中得到的每个单词必须是字典里存在的单词。

EXAMPLE
Input: DAMP, LIKE
Output: DAMP -> LAMP -> LIMP -> LIME -> LIKE

思路:

这其实就是广度优先遍历。遍历过程中,我们需要记录路径,在找到目标单词后,根据记录的路径打印出变形过程。

    int ladderLength(string start, string end, unordered_set<string> &dict) 
    {// The driver function
        map<string, vector<string>> graph; // The graph
        
        // Build the graph according to the method given in:
        //     http://yucoding.blogspot.com/2013/08/leetcode-question-127-word-ladder.html
        for(unordered_set<string>::iterator it = dict.begin(); it!=dict.end(); it++)
        {
	       graph[*it] = findDict(*it, dict); // find out the neighbors of *it
        }
        
        // Do breadth first traversal
        return BFT(start, end, graph);
        
    }
    
    int BFT(string start, string end, map<string, vector<string>>& graph)
    {
        deque<pair<string,int>> queue; // The queue for holding the nodes in the graph
        unordered_set<string> visited; // Mark those nodes that have been visited
        
        queue.push_back( pair<string, int>(start,1) ); // push back the string and its level
        
        while(queue.size()>0)
        {
            pair<string,int> front = queue.front();
            queue.pop_front();
            
            if(front.first==end)
                return front.second;
                
            vector<string> vec = graph[front.first];
            
            for(int i=0; i<vec.size(); i++)
            {
                if(visited.find(vec[i])==visited.end())
                {
                    visited.insert(vec[i]);
                    queue.push_back(pair<string,int>(vec[i], front.second+1) );
                }
            }

        }
        
        return 0;
    }
    
    vector<string> findDict(string str, unordered_set<string> &dict){
    // Find out the neighbors of str in dict
        vector<string> res;
        int sz = str.size();
        string s = str;
        for (int i=0;i<sz;i++){
            s = str;
            for (char j = 'a'; j<='z'; j++){
                s[i]=j;
                if (dict.find(s)!=dict.end()){
                    res.push_back(s);
                }
            }
             
        }
        return res;
    }


你可能感兴趣的:(LeetCode)