This is the problem description:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same.
Test case:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
My issue:
To keep track of the path that the traversal takes to get to the current node, I'm trying to pass in a path array that is updated every time a new node is added to the queue. Currently, the code that updates the path is: q.append((word, level + 1, previous + [top]))
. For some reason, my path array isn't actually updating every time. What did I do wrong?
My code:
import collections
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
representations = {}
for word in wordList:
for i in range(len(word)):
rep = word[:i] + "_" + word[i+1:]
if word[:i] + "_" + word[i+1:] in representations:
representations[rep].append(word)
else:
representations[rep] = [word]
q = collections.deque()
q.append((beginWord, 0, []))
shortest = 0
result = []
visited = {}
while q:
top, level, previous = q.popleft()
if top in visited: continue
if not found:
if top == endWord:
found = True
result.append(path)
shortest = level
else:
visited[top] = True
for i in range(len(top)):
rep = word[:i] + "_" + word[i+1:]
for word in representations[rep]:
q.append((word, level + 1, previous + [top]))
representations[rep] = []
else:
if top == endWord:
result.append(previous + [top])
return result