Skip to content

Instantly share code, notes, and snippets.

@Odomontois
Created December 19, 2020 16:39
Show Gist options
  • Save Odomontois/f0550e68d6ff016b31fa0e9bbfbf6e0f to your computer and use it in GitHub Desktop.
Save Odomontois/f0550e68d6ff016b31fa0e9bbfbf6e0f to your computer and use it in GitHub Desktop.
# 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