Leetcode 127. Word Ladder

     转载请注明出处: http://www.cnblogs.com/gufeiyang

   个人微博:flysea_gu

题意:

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

思路:BFS。 只是普通的BFS。 但是建边的复杂度非常高, 枚举的话应该是n*n*length.这样的话会超时。

解决办法: 构造, 枚举每个word的每个位置,对枚举的位置枚举'a'~‘z’看构造的单词是否在字典中。

AC代码:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
        map<string,int> dis;
        queue<string> q;
        dis[beginWord] = 1;
        q.push(beginWord);
        while(!q.empty())
        {
            string u = q.front();
            q.pop();
            if(u == endWord) return dis[endWord];
            for(int i=0; i<u.length(); i++)
            {
                for(int j=0; j<26; j++)
                {
                    char c = 'a'+j;
                    string v = u;
                    v[i] = c;
                    if(dis.count(v) ==0 && wordList.count(v) != 0)
                    {
                        dis[v] = dis[u] + 1;
                        q.push(v);
                    }
                }
            }
        }
        return 0;
    }
};
View Code

 

posted @ 2016-02-20 17:02  Gu Feiyang  阅读(109)  评论(0)    收藏  举报