150强访谈简单

字梯

“Word Ladder”问题的详细指南和 Python 实现。

问题陈述

简单

使用字典 wordList 从单词 beginWord 到单词 endWord 的转换序列是单词 beginWord -> s1 -> s2 -> ... -> sk 的序列,使得:

- 每对相邻的单词都有一个字母不同。

- 1 <= i <= k 的每个 si 都在 wordList 中。请注意,beginWord 不需要位于 wordList 中。

- sk == endWord。

给定两个单词 beginWord 和 endWord 以及字典 wordList,返回从 beginWord 到 endWord 的最短转换序列中的单词数,如果不存在这样的序列则返回 0。

编写一个函数 ladderLength(beginWord: str, endWord: str, wordList: List[str]) -> int

约束条件
  • 1 <= len(beginWord) <= 10
  • endWord.length == beginWord.length
  • 1 <= len(wordList) <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters
  • All the words in wordList are unique

示例

Example 1
Input
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output
5
Explanation

One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which is 5 words long.

Example 2
Input
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output
0
Explanation

The endWord "cog" is not in wordList, so there is no valid transformation sequence.

Need a Hint?
考虑使用特定于图的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。