# 127. Word Ladder

<https://leetcode.com/problems/word-ladder/>

## solution

```python
class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        visited = set()
        queue = collections.deque()
        queue.append(beginWord)
        visited.add(beginWord)  # 注意防止图遍历成环

        step = 0
        while queue:
            step += 1
            for _ in range(len(queue)):
                node = queue.popleft()
                for i in range(len(node)):
                    for c in string.ascii_lowercase:
                        new_word = node[:i] + c + node[i+1:]
                        if new_word in wordList and new_word not in visited:
                            if new_word == endWord:
                                return step + 1

                            queue.append(new_word)
                            visited.add(new_word)
        return 0
```

```python
class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        wordset = set(wordList)  # hashset也是加速方法
        queue = collections.deque()
        queue.append((beginWord, 1))
        word_length = len(beginWord)
        while queue:
            word, step = queue.popleft()
            if word == endWord:
                return step
            for i in range(word_length):
                for c in "abcdefghijklmnopqrstuvwxyz":
                    new_word = word[:i] + c + word[i+1:]
                    if new_word in wordset:
                        wordset.remove(new_word)
                        queue.append((new_word, step+1))
        return 0
```

时间复杂度：O(∣wordList∣⋅26^(wordList\[i]))\
空间复杂度：O(∣wordList∣)

* 双向bfs

```python
```

## follow up

[126 Word Ladder II](/mle-interview/01_leetcode/07_dfs/126.-word-ladder-ii.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/08_bfs/127.-word-ladder.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
