Approach
Depth-first search
For Word Search II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 50 lines of Python from the credited upstream file 212.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode:2 def __init__(self):3 self.children: dict[str, TrieNode] = {}4 self.word: str | None = None5 6 7class Solution:8 def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:9 m = len(board)10 n = len(board[0])11 ans = []12 root = TrieNode()13 14 def insert(word: str) -> None:15 node = root16 for c in word:17 node = node.children.setdefault(c, TrieNode())18 node.word = word19 20 for word in words:21 insert(word)22 23 def dfs(i: int, j: int, node: TrieNode) -> None:24 if i < 0 or i == m or j < 0 or j == n:25 return26 if board[i][j] == '*':27 return28 29 c = board[i][j]30 if c not in node.children:31 return32 33 child = node.children[c]34 if child.word:35 ans.append(child.word)36 child.word = None37 38 board[i][j] = '*'39 dfs(i + 1, j, child)40 dfs(i - 1, j, child)41 dfs(i, j + 1, child)42 dfs(i, j - 1, child)43 board[i][j] = c44 45 for i in range(m):46 for j in range(n):47 dfs(i, j, root)48 49 return ans50