Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 126 · State-Space / Transformation BFS

Word Ladder II

LeetCode 126 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

BFS for levels, then DFS backwards along level − 1.

ಕಠಿಣHash TableStringBacktrackingBreadth-First SearchBidirectional Search
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Word Ladder II (LeetCode 126) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — State-Space / Transformation BFS ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

First BFS from the begin word to label each word with its level — that defines the shortest paths. Then backtrack from the end word, only stepping to words exactly one level lower, so only shortest paths are produced.

Approach

  1. 1

    Version 1: BFS builds a layered adjacency, DFS forward.

  2. 2

    Version 2: BFS records word_levels, stopping at the end word.

  3. 3

    DFS from endWord to words whose level is one less.

  4. 4

    Reverse each path.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ

1
BFS layers + forward DFSslower

Build all layered edges.

2
BFS levels + backward DFSAcceptedfaster

Walk back by levels.

BFS layers + forward DFSPythonslower
class Solution:
    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
        #bfs to get neighbour word
        #dfs/backtracking to create the paths
        #special adj list to get the word and it's next words as keys
        #visited map as node as key and value as level
        words = set(wordList)
        if endWord not in words:
            return []
        adjList = defaultdict(set)
        q = deque([beginWord])
        visited = defaultdict(int)
        visited[beginWord]=0
        while q:
            cur_word=q.popleft()
            for i in range(len(cur_word)):
                for j in range(26):
                    char = chr(97+j)
                    if char==cur_word[i]:
                        continue
                    new_word = cur_word[:i]+char+cur_word[i+1:]
                    if new_word in words:
                        if new_word not in visited:
                            adjList[cur_word].add(new_word)
                            q.append(new_word)
                            visited[new_word]=visited[cur_word]+1
                        elif visited[new_word]==visited[cur_word]+1: #already visited but it's just on the next level
                            adjList[cur_word].add(new_word)
        res=[]
        def dfs(word, path):
            if word == endWord:
                res.append(path[:])
                return
            for adj_word in adjList[word]:
                path.append(adj_word)
                dfs(adj_word,path)
                path.pop()
        dfs(beginWord,[beginWord])
        return res
BFS levels + backward DFSPythonfaster
class Solution:
    def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
       #first bfs to get level
       #second dfs - from leaf to top to get the path
        words = set(wordList)
        if endWord not in words:
            return []
        word_levels = defaultdict(int)
        word_levels[beginWord]=1
        q = deque([beginWord])
        words.discard(beginWord)
        while q:
            cur_word=q.popleft()
            if cur_word==endWord:
                break
            for i in range(len(cur_word)):
                for j in range(26):
                    char = chr(97+j)
                    if char==cur_word[i]:
                        continue
                    new_word = cur_word[:i]+char+cur_word[i+1:]
                    if new_word in words:
                            q.append(new_word)
                            word_levels[new_word]=word_levels[cur_word]+1
                            words.remove(new_word)
        print(word_levels)
        res=[]
        def dfs(next_word,path):
            if next_word == beginWord:
                res.append(path[::-1])
                return
            next_word_level=word_levels[next_word]
            for i in range(len(next_word)):
                for j in range(26):
                    char = chr(97+j)
                    if char==next_word[i]:
                        continue
                    prev_word = next_word[:i]+char+next_word[i+1:]
                    if prev_word in word_levels and word_levels[prev_word]+1==next_word_level:
                            path.append(prev_word)
                            dfs(prev_word,path)
                            path.pop()
        dfs(endWord,[endWord])
        return res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Word Ladder II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Word Ladder II ಹಿಂದಿನ intuition ಏನು?

First BFS from the begin word to label each word with its level — that defines the shortest paths. Then backtrack from the end word, only stepping to words exactly one level lower, so only shortest paths are produced.

Word Ladder II (LeetCode 126) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Version 1: BFS builds a layered adjacency, DFS forward. 2. Version 2: BFS records word_levels, stopping at the end word. 3. DFS from endWord to words whose level is one less. 4. Reverse each path.

Word Ladder II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: exponential in the number of paths. Space: O(N · L). (Accepted approach: BFS levels + backward DFS.)

Word Ladder II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Searching backwards avoids exploring dead branches. The print() in version 2 is leftover debug output.

Word Ladder II ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?

BFS layers + forward DFS (slower): Build all layered edges. BFS levels + backward DFS (faster): Walk back by levels.