Word Ladder (Leetcode 127)

BFS

Problem Link: https://leetcode.com/problems/word-ladder/

class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        
        # The set acts as the visited array
        # as we remove the words which are already seen
        s=set(wordList)
        q=[[beginWord,1]]
        
        # BFS
        while(len(q)>0):
            for _ in range(len(q)):
                
                word,count=q.pop()
                print(word)
                for i in range(len(word)):
                    tempword=word
                    for j in range(97,123):
                        
                        tempword=tempword[:i]+chr(j)+tempword[i+1:]
                        if(tempword in s):
                            q.insert(0,[tempword,count+1])
                            s.remove(tempword)
                            
                if(word==endWord):
                    return count
        return 0      

Last updated