Leetcode:Word Ladder 单词接龙

Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

Only one letter can be changed at a time
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.

 

解题分析:

首先想到的是,对当前单词的每个字母进行变换(相当于状态扩展),然后在词典中查找,如果查找成功,则继续扩展

注意,这题要求的是最短长度,只要提及最短,必然首先BFS

class Solution {
public:
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        std::deque<std::string> que;
        que.push_back(start);
        que.push_back("");
        int res = 1;
        while (!que.empty()) {
            std::string cur = que.front();
            que.pop_front();
            if (cur != "") {
                for (int i = 0; i < cur.size(); ++i) {
                    char tmp = cur.at(i); 
                    for (char c = 'a'; c <= 'z'; ++c) {
                        if (c == cur.at(i)) {
                            continue;
                        }
                        cur.at(i) = c;     // 扩展状态
                        if (cur == end) {  // 收敛 return res + 1;
                        }
                        if (dict.find(cur) != dict.end()) {
                            que.push_back(cur);
                            dict.erase(cur); // 注意一旦查找成功,必须从词典中删除该单词,避免 hit->hot->hit死循环
                        }
                    }
                    cur.at(i) = tmp;     // 恢复原状态
                }
            } else if (!que.empty()) {
                que.push_back("");
                res++;
            }
        }
        return 0;
    }
};

注意:每个单词扩展完状态(26种情况)之后,que需要push一个空字符串,这个空字符标志BFS每层之间的分层

 

Word Ladder II

在上一題的基础之上,需要求出BFS路径

 

你可能感兴趣的:(LeetCode)