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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。