-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordLadderII.py
More file actions
28 lines (25 loc) · 982 Bytes
/
wordLadderII.py
File metadata and controls
28 lines (25 loc) · 982 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/word-ladder-ii/
# Author: Miao Zhang
# Date: 2021-01-20
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
wordlist=set(wordList)
res= []
layer = {}
layer[beginWord] = [[beginWord]]
while layer:
newlayer = collections.defaultdict(list)
for w in layer:
if w == endWord:
res.extend(k for k in layer[w])
else:
for i in range(len(w)):
for c in "abcdefghijklmnopqrstuvwxyz":
newword=w[:i] + c + w[i+1:]
if newword in wordlist:
newlayer[newword] += [j+[newword] for j in layer[w]]
wordlist -=set(newlayer.keys())
layer = newlayer
return res