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
- 56 lines of Java from the credited upstream file 212.java.
- The implementation visibly relies on sequence storage.
- 4 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 public TrieNode[] children = new TrieNode[26];3 public String word;4}5 6class Solution {7 public List<String> findWords(char[][] board, String[] words) {8 for (final String word : words)9 insert(word);10 11 List<String> ans = new ArrayList<>();12 13 for (int i = 0; i < board.length; ++i)14 for (int j = 0; j < board[0].length; ++j)15 dfs(board, i, j, root, ans);16 17 return ans;18 }19 20 private TrieNode root = new TrieNode();21 22 private void insert(final String word) {23 TrieNode node = root;24 for (final char c : word.toCharArray()) {25 final int i = c - 'a';26 if (node.children[i] == null)27 node.children[i] = new TrieNode();28 node = node.children[i];29 }30 node.word = word;31 }32 33 private void dfs(char[][] board, int i, int j, TrieNode node, List<String> ans) {34 if (i < 0 || i == board.length || j < 0 || j == board[0].length)35 return;36 if (board[i][j] == '*')37 return;38 39 final char c = board[i][j];40 TrieNode child = node.children[c - 'a'];41 if (child == null)42 return;43 if (child.word != null) {44 ans.add(child.word);45 child.word = null;46 }47 48 board[i][j] = '*';49 dfs(board, i + 1, j, child, ans);50 dfs(board, i - 1, j, child, ans);51 dfs(board, i, j + 1, child, ans);52 dfs(board, i, j - 1, child, ans);53 board[i][j] = c;54 }55}56