Approach
Depth-first search
For Word Squares, 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
- 82 lines of Java from the credited upstream file 425.java.
- The implementation visibly relies on sequence storage.
- 6 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 List<String> startsWith = new ArrayList<>();4}5 6class Trie {7 public Trie(final String[] words) {8 for (final String word : words)9 insert(word);10 }11 12 public List<String> findBy(final String prefix) {13 TrieNode node = root;14 for (final char c : prefix.toCharArray()) {15 final int i = c - 'a';16 if (node.children[i] == null)17 return new ArrayList<>();18 node = node.children[i];19 }20 return node.startsWith;21 }22 23 private TrieNode root = new TrieNode();24 25 private void insert(final String word) {26 TrieNode node = root;27 for (final char c : word.toCharArray()) {28 final int i = c - 'a';29 if (node.children[i] == null)30 node.children[i] = new TrieNode();31 node = node.children[i];32 node.startsWith.add(word);33 }34 }35}36 37class Solution {38 public List<List<String>> wordSquares(String[] words) {39 if (words.length == 0)40 return new ArrayList<>();41 42 final int n = words[0].length();43 List<List<String>> ans = new ArrayList<>();44 List<String> path = new ArrayList<>();45 Trie trie = new Trie(words);46 47 for (final String word : words) {48 path.add(word);49 dfs(trie, n, path, ans);50 path.remove(path.size() - 1);51 }52 53 return ans;54 }55 56 private void dfs(Trie trie, final int n, List<String> path, List<List<String>> ans) {57 if (path.size() == n) {58 ans.add(new ArrayList<>(path));59 return;60 }61 62 final String prefix = getPrefix(path);63 64 for (final String s : trie.findBy(prefix)) {65 path.add(s);66 dfs(trie, n, path, ans);67 path.remove(path.size() - 1);68 }69 }70 71 72 73 74 private String getPrefix(List<String> path) {75 StringBuilder sb = new StringBuilder();76 final int index = path.size();77 for (final String s : path)78 sb.append(s.charAt(index));79 return sb.toString();80 }81}82