-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordLadder.py
More file actions
48 lines (41 loc) · 1.67 KB
/
Copy pathWordLadder.py
File metadata and controls
48 lines (41 loc) · 1.67 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import collections
class Solution:
def wordLader(self, beginWord: str, endWord: str, wordList: list) -> int:
def adjancyMap(beginWord: str, endWord: str, wordList: list) -> int:
queue = collections.deque([beginWord])
if not endWord == wordList[-1]:
return -1
adjacency = {x: [] for x in wordList}
adjacency[beginWord] = []
for i in range(len(wordList)):
if beginWord != wordList[i]:
diff = 0
j = 0
for j in range(len(beginWord)):
if beginWord[j] != wordList[i][j]:
diff += 1
j += 1
if diff <= 1:
adjacency[beginWord].append(wordList[i])
k = 1
m = 0
while k < len(wordList):
if wordList[k] != wordList[m]:
diff = 0
while j < len(wordList[m]):
if wordList[m][j] != wordList[k][j]:
diff += 1
if diff <= 1:
adjacency[wordList[m]].append(wordList[k])
k, m = k + 1, m + 1
return adjacency
adj = adjancyMap(beginWord, endWord, wordList)
word = [beginWord, adj[beginWord]]
transformation = [] # O(n) space
while word: # O(n+m) time m-> some diplicates
transformation.append(word[0])
if not word[1]:
word = []
else:
word = [word[1][0], adj[word[1][0]]]
return (transformation, len(transformation))