Word Ladder
public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
Set<String> reached = new HashSet<String>();
reached.add(beginWord);
wordDict.add(endWord);
int distance = 1;
while (!reached.contains(endWord)) {
Set<String> toAdd = new HashSet<String>();
for (String each : reached) {
for (int i = 0; i < each.length(); i++) {
char[] chars = each.toCharArray();
for (char ch = 'a'; ch <= 'z'; ch++) {
chars[i] = ch;
String word = new String(chars);
if (wordDict.contains(word)) {
toAdd.add(word);
wordDict.remove(word);
}
}
}
}
distance++;
if (toAdd.size() == 0) return 0;
reached = toAdd;
}
return distance;
}
from collections import defaultdict
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList or not endWord or not beginWord or not wordList:
return 0
L = len(beginWord)
all_combo_dict = defaultdict(list)
for word in wordList:
for i in range(L):
all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)
queue = deque([(beginWord, 1)])
visited = set(beginWord)
while queue:
current_word, level = queue.popleft()
for i in range(L):
intermediate_word = current_word[:i] + "*" + current_word[i+1:]
for word in all_combo_dict[intermediate_word]:
if word == endWord:
return level + 1
if word not in visited:
visited.add(word)
queue.append((word, level + 1))
return 0
最后更新于
这有帮助吗?