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.