本文完整拆解 LeetCode 79 Word Search 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Word Search 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
內容目錄
TogglePython
# time complexity: O(c*3^l)
# space complexity: O(l)
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def backtrack(suffix: str, r: int, c: int):
if len(suffix) == 0:
return True
if not (0 <= r < ROW and 0 <= c < COL) or suffix[0] != board[r][c]:
return False
result = False
originalChar = board[r][c]
board[r][c] = "#"
for dr,dc in ([1,0],[0,1],[-1,0],[0,-1]):
result = backtrack(suffix[1:], r+dr, c+dc)
if result:
break
board[r][c] = originalChar
return result
ROW = len(board)
COL = len(board[0])
for row in range(ROW):
for col in range(COL):
if backtrack(word, row, col):
return True
return False
board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]]
word = "ABCCED"
print(Solution().exist(board, word))
Word Search 解題思路
在網格中找單字,本質是從每個起點出發做深度優先搜尋,並在過程中回溯。關鍵技巧是「原地標記」:走過的格子暫時改成特殊字元,避免同一條路徑重複使用同一格;遞迴返回時再改回來,這樣就不必額外開一個 visited 矩陣。
Word Search 演算法步驟
- 對網格中每一格呼叫 dfs(i, j, 0),嘗試以它為單字起點。
- dfs 中先檢查越界、字元不符就回傳 false;索引等於單字長度時回傳 true。
- 把目前格子暫存後改成 # 之類的標記,代表這條路徑已使用。
- 往上下左右四個方向遞迴,任一成功就回傳 true;全部失敗後把格子還原再回傳 false。
Word Search 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(m·n·4^L) |
| 空間複雜度 | O(L) |
L 是單字長度。每個起點最多展開四叉樹深度 L,所以最壞時間是 O(m·n·4^L),實務上因為字元不符會大量剪枝。空間主要是遞迴堆疊深度 O(L),原地標記讓額外矩陣省下來。
Word Search 的邊界情況與常見錯誤
- 還原格子一定要寫在所有方向遞迴之後,漏掉會污染其他路徑。
- 單字長度大於網格總格數時可以直接回傳 false。
- 同一格不能重複使用,但不同起點的搜尋彼此獨立。
- 空單字依題意通常回傳 true,但多數測資不會出現。
Word Search 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 額外 visited 矩陣 + DFS | O(m·n·4^L) | O(m·n) | 邏輯相同但多一個矩陣 |
| BFS 逐層搜尋 | O(m·n·4^L) | O(4^L) | 佇列會爆,不適合路徑型搜尋 |
| DFS + 原地標記回溯 | O(m·n·4^L) | O(L) | 本文採用 |



