From 23e8c3945981c22060fa565926672c4e650479fa Mon Sep 17 00:00:00 2001 From: YTLim-1206 Date: Sat, 14 Nov 2026 17:25:27 +0800 Subject: [PATCH] Add Python solution for Word Ladder (practice256) --- solutions/python/practice256.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/solutions/python/practice256.py b/solutions/python/practice256.py index ca6c826..b33012d 100644 --- a/solutions/python/practice256.py +++ b/solutions/python/practice256.py @@ -1,11 +1,32 @@ # Problem: Word Ladder # Source: https://leetcode.com/problems/word-ladder/ -# Note: Finds the length of the shortest transformation sequence between two words, changing one letter at a time using dictionary words. -# Status: 🔄 IN PROGRESS - Implementation needed -# TODO: Implement BFS for shortest transformation sequence +# Note: Implement BFS for shortest transformation sequence using deque +# Status: ✅ Done -def word_ladder(word): - pass +from collections import deque -dictionary = {"hot", "dot", "dog", "lot", "log", "cog"} +def word_ladder(beginWord, endWord, wordList): + wordSet = set(wordList) + if endWord not in wordSet: + return 0 + queue = deque([(beginWord, 1)]) + wordSet.discard(beginWord) + + # BFS + while queue: + word, steps = queue.popleft() + if word == endWord: + return steps + for i in range(len(word)): + for character in "abcdefghijklmnopqrstuvwxyz": + if character == word[i]: + continue + newWord = word[:i] + character + word[i+1:] + if newWord in wordSet: + wordSet.remove(newWord) + queue.append((newWord, steps + 1)) + return 0 + +# Example +dictionary = ["hot", "dot", "dog", "lot", "log", "cog"] print(word_ladder("hit", "cog", dictionary)) # 5