来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/word-ladder/
字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列 beginWord -> s1 -> s2 -> ... -> sk:
给你两个单词 beginWord 和 endWord 和一个字典 wordList ,返回 从 beginWord 到 endWord 的 最短转换序列 中的 单词数目 。如果不存在这样的转换序列,返回 0 。
示例 1:
输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
输出:5
解释:一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。
示例 2:
输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
输出:0
解释:endWord "cog" 不在字典中,所以无法进行转换。
提示:
python实现
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if beginWord == endWord:
return 0
if endWord not in wordList:
return 0
wordList = set(wordList)
queue = [(beginWord, 1)]
while queue:
current_str, step = queue.pop(0)
for i, x in enumerate(current_str):
for y in 'abcdefghijklmnopqrstuvwxyz':
if x != y:
next_str = current_str[:i] + y + current_str[i+1:]
if next_str in wordList:
if next_str == endWord:
return step+1
wordList.remove(next_str)
queue.append((next_str, step+1))
return 0
c++实现
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> cnt;
queue<pair<string, int>> q;
string key = "abcdefghijklmnopqrstuvwxyz";
for(auto &w: wordList)
cnt.emplace(w);
if (beginWord == endWord)
return 0;
if (!cnt.count(endWord))
return 0;
q.push({beginWord, 1});
while (!q.empty()) {
pair curr = q.front();
q.pop();
string curr_string = curr.first;
int curr_step = curr.second;
for (int i=0; i< curr_string.size(); i++) {
for(int j=0; j<key.size(); j++) {
if (key[j] != curr_string[i]) {
string nxt = curr_string;
nxt[i] = key[j];
if (cnt.count(nxt)){
if (nxt == endWord)
return curr_step+1;
cnt.erase(nxt);
q.push({nxt, curr_step+1});
}
}
}
}
}
return 0;
}
};
复杂度分析