Approach
Depth-first search
For Pyramid Transition Matrix, 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
- 31 lines of Java from the credited upstream file 756.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 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 Solution {2 public boolean pyramidTransition(String bottom, List<String> allowed) {3 Map<String, List<Character>> prefixToBlocks = new HashMap<>();4 5 for (final String a : allowed) {6 final String lowerBlocks = a.substring(0, 2);7 prefixToBlocks.putIfAbsent(lowerBlocks, new LinkedList<>());8 prefixToBlocks.get(lowerBlocks).add(a.charAt(2));9 }10 11 return dfs(bottom, "", 0, prefixToBlocks);12 }13 14 private boolean dfs(final String row, final String nextRow, int i,15 Map<String, List<Character>> prefixToBlocks) {16 if (row.length() == 1)17 return true;18 if (nextRow.length() + 1 == row.length())19 return dfs(nextRow, "", 0, prefixToBlocks);20 21 final String prefix = row.substring(i, i + 2);22 23 if (prefixToBlocks.containsKey(prefix))24 for (final char c : prefixToBlocks.get(prefix))25 if (dfs(row, nextRow + c, i + 1, prefixToBlocks))26 return true;27 28 return false;29 }30}31