本文完整拆解 LeetCode 212 Word Search II 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Word Search II 一次弄懂。
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 board of characters and a list of strings words, return all words on the board.
Each word must 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 in a word.
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: ["eat","oath"]
Example 2:
Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: []
Constraints:
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j]is a lowercase English letter.1 <= words.length <= 3 * 1041 <= words[i].length <= 10words[i]consists of lowercase English letters.- All the strings of
wordsare unique.
內容目錄
TogglePython
# time complexity: O(M(4*3^(L-1)))
# space complexity: O(n)
from typing import List
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
WORDKEY = "$"
trie = {}
for word in words:
node = trie
for letter in word:
node = node.setdefault(letter, {})
node[WORDKEY] = word
rowNum = len(board)
colNum = len(board[0])
matchedWords = []
def backtracking(row, col, parent):
letter = board[row][col]
currNode = parent[letter]
wordMatch = currNode.pop(WORDKEY, False)
if wordMatch:
matchedWords.append(wordMatch)
board[row][col] = "#"
for rowOffset, colOffset in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
newRow, newCol = row + rowOffset, col + colOffset
if (
newRow < 0
or newRow >= rowNum
or newCol < 0
or newCol >= colNum
):
continue
if not board[newRow][newCol] in currNode:
continue
backtracking(newRow, newCol, currNode)
board[row][col] = letter
if not currNode:
parent.pop(letter)
for row in range(rowNum):
for col in range(colNum):
if board[row][col] in trie:
backtracking(row, col, trie)
return matchedWords
# time complexity: O(n*3^l)
# space complexity: O(m)
class TrieNode:
def __init__(self, char=""):
self.char = char
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children.get(c)
node.isEnd = True
def startsWith(self, prefix):
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True
def removeChars(self, word):
node = self.root
childList = []
for c in word:
childList.append([node, c])
node = node.children[c]
for parent, childChar in reversed(childList):
target = parent.children[childChar]
if target.children:
return
del parent.children[childChar]
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
def dfs(trieForWords: Trie, node: TrieNode, grid: List[List[str]], row: int, col: int, result: List[str], word=""):
if node.isEnd:
result.append(word)
node.isEnd = False
trieForWords.removeChars(word)
if 0 <= row < ROW and 0 <= col < COL:
char = grid[row][col]
child = node.children.get(char)
if child is not None:
word += char
grid[row][col] = None
for dR, dC in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
dfs(trieForWords, child, grid,
row + dR, col + dC, result, word)
grid[row][col] = char
ROW = len(board)
COL = len(board[0])
trieForWords = Trie()
result = []
for word in words:
trieForWords.insert(word)
for r in range(ROW):
for c in range(COL):
dfs(trieForWords, trieForWords.root, board, r, c, result)
return result
board = [["o", "a", "a", "n"],
["e", "t", "a", "e"],
["i", "h", "k", "r"],
["i", "f", "l", "v"]]
words = ["oath", "pea", "eat", "rain"]
print(Solution().findWords(board, words))
Word Search II 解題思路
如果對每個單字各跑一次 Word Search,重複的前綴會被走訪無數次。正解是把所有單字先建成 Trie,然後只在網格上做「一次」DFS——沿路同步在 Trie 上移動,走到不存在的前綴就立刻剪枝。找到單字後把 Trie 節點的單字清空,可避免重複輸出並進一步剪枝。
Word Search II 演算法步驟
- 把 words 全部插入 Trie,終點節點直接存整個單字字串。
- 對網格每一格呼叫 dfs(i, j, trieNode)。
- dfs 中取得目前字元,若 Trie 節點沒有該子節點就返回;若子節點存有單字就收進答案並清空。
- 把格子暫時標記為已訪,往四方向遞迴,返回後還原格子。
Word Search II 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(m·n·4^L) |
| 空間複雜度 | O(N·L) |
L 是最長單字長度。最壞上界仍是 O(m·n·4^L),但 Trie 剪枝讓實際分支遠少於此——只要前綴不存在就立刻停止。空間主要是 Trie 的 O(N·L)。
Word Search II 的邊界情況與常見錯誤
- 找到單字後要把節點上的字串清空,否則同一個單字可能被重複加入。
- 格子標記一定要在遞迴後還原。
- 單字清單可能很大,先建 Trie 的前置成本是值得的。
- 可額外剪掉沒有子節點且已無單字的 Trie 分支,加速明顯。
Word Search II 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 對每個單字跑一次 Word Search | O(W·m·n·4^L) | O(L) | 單字一多就爆炸 |
| 先收集網格所有路徑再比對 | — | — | 路徑數量指數級,不可行 |
| Trie + 單次網格 DFS | O(m·n·4^L) | O(N·L) | 本文採用 |


