150強訪談簡單

單字搜尋 II

“Word Search II”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個 m x n 的字元板和一個字串單字列表,傳回板上的所有單字。

每個單字必須由順序相鄰單元格的字母構成,其中相鄰單元格水平或垂直相鄰。同一字母單元不得在一個單字中使用多次。

寫一個函數 findWords(board: List[List[str]], words: List[str]) -> List[str]

約束條件
  • m == len(board)
  • n == len(board[i])
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter
  • 1 <= len(words) <= 3 * 10^4
  • 1 <= len(words[i]) <= 10
  • words consist of lowercase English letters
  • All the strings in words are unique

範例

Example 1
Input
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output
["oath","eat"]
Explanation

The words "oath" and "eat" can be found on the board. "pea" and "rain" cannot.

Example 2
Input
board = [["a","b"],["c","d"]], words = ["abcb"]
Output
[]
Explanation

The word "abcb" requires using the 'b' cell twice, which is invalid.

Need a Hint?
考慮使用 Trie 特定的資料結構,例如集合或堆疊。
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 資源

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