leetcode - 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.
class Solution {
    public:
        int ladderLength(std::string start, std::string end, std::unordered_set<std::string> &dict) {
            std::unordered_map<std::string, int> dis;
            std::queue<std::string> q;
            dis[start] = 1;
            q.push(start);
            while (!q.empty()) {
                std::string word = q.front(); q.pop();
                if (word == end) break;
                for (int i = 0; i < word.size(); i++) {
                    for (int j = 0; j < 26; j++) {
                        std::string newWord = word;
                        newWord[i] = 'a' + j;
                        if (dict.count(newWord) > 0 && dis.count(newWord) == 0) {
                            dis[newWord] = dis[word] + 1;
                            q.push(newWord);
                        }
                    }
                }
            }
            if (dis.count(end) == 0) return 0;
            return dis[end];
        }
};


posted @ 2015-12-10 16:33  blfshiye  阅读(118)  评论(0编辑  收藏  举报