Word Search II 解题教学:3 种解法完整比较|LeetCode 212 Best Practice

Word Search II 解题教学示意图|LeetCode 212

本文完整拆解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 mxn 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.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 10 4
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.
				
					# 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 演算法步骤

  1. 把words 全部插入Trie,终点节点直接存整个单字字串。
  2. 对网格每一格呼叫dfs(i, j, trieNode)。
  3. dfs 中取得目前字元,若Trie 节点没有该子节点就返回;若子节点存有单字就收进答案并清空。
  4. 把格子暂时标记为已访,往四方向递回,返回后还原格子。

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 SearchO(W·m·n·4^L)O(L)单字一多就爆炸
先收集网格所有路径再比对——路径数量指数级,不可行
Trie + 单次网格DFSO(m·n·4^L)O(N·L)本文采用