Approach
Depth-first search
For Android Unlock Patterns, 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
- 33 lines of Python from the credited upstream file 351.py.
- The implementation visibly relies on ordered 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 Solution:2 def numberOfPatterns(self, m: int, n: int) -> int:3 seen = set()4 accross = [[0] * 10 for _ in range(10)]5 6 accross[1][3] = accross[3][1] = 27 accross[1][7] = accross[7][1] = 48 accross[3][9] = accross[9][3] = 69 accross[7][9] = accross[9][7] = 810 accross[1][9] = accross[9][1] = accross[2][8] = accross[8][2] = \11 accross[3][7] = accross[7][3] = accross[4][6] = accross[6][4] = 512 13 def dfs(u: int, depth: int) -> int:14 if depth > n:15 return 016 17 seen.add(u)18 ans = 1 if depth >= m else 019 20 for v in range(1, 10):21 if v == u or v in seen:22 continue23 accrossed = accross[u][v]24 if not accrossed or accrossed in seen:25 ans += dfs(v, depth + 1)26 27 seen.remove(u)28 return ans29 30 31 32 return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1)33