Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 127 · State-Space / Transformation BFS

Word Ladder

LeetCode 127 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

BFS generating one-letter neighbours; remove words once used.

கடினம்Hash TableStringBreadth-First SearchBidirectional Search
LeetCode இல் திற ↗

நான் Word Ladder (LeetCode 127) ஐ இப்படித் தீர்த்தேன் — State-Space / Transformation BFS பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Words are nodes and one-letter changes are edges. The shortest transformation is a BFS from the begin word, generating neighbours by trying every letter in every position.

Approach

  1. 1

    Put the word list in a set; end word missing → 0.

  2. 2

    BFS from (beginWord, 1).

  3. 3

    For each position and letter, a word in the set is enqueued and removed.

  4. 4

    Return the level when the end word is popped.

நான் எப்படித் தீர்த்தேன்

BFSPythonO(N·L·26) time
class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        #Simple bfs - step by step
        #if begin word in word list remove 
        #if end word not in word list return 0
        #change char by char- if new word is in word list, add new node and steps+1
        wordList=set(wordList)
        if endWord not in wordList:
            return 0
        if beginWord in wordList:
            wordList.remove(beginWord)

        q = deque([(beginWord,1)])
        while q:
            cur_word,steps = q.popleft()
            if cur_word==endWord:
                return steps
            for i in range(len(cur_word)):
                for j in range(26):
                    new_char = chr(97+j)
                    new_word = cur_word[:i]+new_char+cur_word[i+1:]
                    if new_word in wordList:
                        q.append((new_word,steps+1))
                        wordList.remove(new_word)
        return 0
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Word Ladder — அடிக்கடி கேட்கப்படும் கேள்விகள்

Word Ladder பின்னாலுள்ள intuition என்ன?

Words are nodes and one-letter changes are edges. The shortest transformation is a BFS from the begin word, generating neighbours by trying every letter in every position.

Word Ladder (LeetCode 127) ஐ எப்படித் தீர்ப்பது?

1. Put the word list in a set; end word missing → 0. 2. BFS from (beginWord, 1). 3. For each position and letter, a word in the set is enqueued and removed. 4. Return the level when the end word is popped.

Word Ladder இன் time மற்றும் space complexity என்ன?

Time: O(N · L · 26). Space: O(N). (Accepted approach: BFS.)

Word Ladder இல் பொதுவான தவறுகள் என்ன?

Removing words from the set doubles as the visited set.