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

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

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

思路:

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

    int ladderLength(string start, string end, unordered_set &dict) 
    {// The driver function
        map> 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::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>& graph)
    {
        deque> queue; // The queue for holding the nodes in the graph
        unordered_set visited; // Mark those nodes that have been visited
        
        queue.push_back( pair(start,1) ); // push back the string and its level
        
        while(queue.size()>0)
        {
            pair front = queue.front();
            queue.pop_front();
            
            if(front.first==end)
                return front.second;
                
            vector vec = graph[front.first];
            
            for(int i=0; i(vec[i], front.second+1) );
                }
            }

        }
        
        return 0;
    }
    
    vector findDict(string str, unordered_set &dict){
    // Find out the neighbors of str in dict
        vector res;
        int sz = str.size();
        string s = str;
        for (int i=0;i


你可能感兴趣的:(字符串)