150強訪談簡單

單字搜尋

“單字搜尋”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個 m x n 字元板網格和一個字串單詞,如果單字存在於網格中,則傳回 true。

該單字可以由順序相鄰的單元格的字母構成,其中相鄰的單元格水平或垂直相鄰。同一字母單元不得使用多次。

實作函數 exist(board: list, word: str) -> bool

約束條件
  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters

範例

Example 1
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED"
Output
True
Explanation

The word ABCCED can be traced: A(0,0)->B(0,1)->C(0,2)->C(1,2)->E(2,2)->D(2,1).

Example 2
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE"
Output
True
Explanation

The word SEE can be traced: S(1,3)->E(2,3)->E(2,2).

Example 3
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB"
Output
False
Explanation

Cannot trace ABCB without reusing cells.

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

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