Created
December 19, 2020 16:39
-
-
Save Odomontois/f0550e68d6ff016b31fa0e9bbfbf6e0f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# noinspection PyPep8Naming | |
class Solution: | |
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: | |
d = defaultdict(list) | |
for word in wordList: | |
for i in range(len(word)): | |
d[word[:i], word[i + 1:]].append(word) | |
seen = {beginWord} | |
q = [beginWord] | |
steps = 1 | |
while q: | |
new_q = [] | |
for word in q: | |
if word == endWord: | |
return steps | |
for i in range(len(word)): | |
for w in d[word[:i], word[i + 1:]]: | |
if w not in seen: | |
seen.add(w) | |
new_q.append(w) | |
steps += 1 | |
q = new_q | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment