I am working on Word Ladder - LeetCode
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence 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 0 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.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.
Example 2:
Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
My Approach:
- Create a graph with word distances
- Calculate the distance to the endWord using BFS
Code:
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
graph = {}
wordList = [beginWord] + wordList if beginWord not in wordList else wordList
for i in range(len(wordList)):
wordU = wordList[i]
# Compute distances and prepare a graph when the distance is equal to one
for j in range(i+1, len(wordList)):
wordV = wordList[j]
if wordU not in graph.keys():
graph[wordU] = []
if wordV not in graph.keys():
graph[wordV] = []
if self.word_difference(wordU, wordV) == 1:
graph[wordU].append(wordV)
graph[wordV].append(wordU)
visited = set()
queue = [beginWord]
distances = {w:1 for w in queue} # since the first word is 1 we are putting 2 here for the root
return self.BFS(graph, endWord, visited, queue, distances)
def word_difference(self, word1, word2):
# Compute the difference in words
distance = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
distance += 1
return distance
def BFS(self, graph, endNode, visited, queue, distances):
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
if node == endNode:
return distances[node]
for neighbour in graph[node]:
if neighbour not in visited:
visited.add(neighbour)
distances[neighbour] = distances[node] + 1
queue.append(neighbour)
return 0
The problem is that the above code is failing on a test case with large word list.
The discussions forum had a solution which took a similar approach but is clearing all the test cases. How can I optimize my solution?