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
- 42 lines of C++ from the credited upstream file 351.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block 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:3 int numberOfPatterns(int m, int n) {4 int ans = 0;5 vector<vector<int>> across(10, vector<int>(10));6 vector<bool> seen(10);7 8 across[1][3] = across[3][1] = 2;9 across[1][7] = across[7][1] = 4;10 across[3][9] = across[9][3] = 6;11 across[7][9] = across[9][7] = 8;12 across[1][9] = across[9][1] = across[2][8] = across[8][2] = across[3][7] =13 across[7][3] = across[4][6] = across[6][4] = 5;14 15 ans += dfs(m, n, 1, 1, seen, across) * 4; 16 ans += dfs(m, n, 2, 1, seen, across) * 4; 17 ans += dfs(m, n, 5, 1, seen, across); 18 return ans;19 }20 21 private:22 int dfs(int m, int n, int u, int depth, vector<bool>& seen,23 const vector<vector<int>>& across) {24 if (depth > n)25 return 0;26 27 seen[u] = true;28 int ans = depth >= m ? 1 : 0;29 30 for (int v = 1; v <= 9; ++v) {31 if (v == u || seen[v])32 continue;33 const int acrossed = across[u][v];34 if (acrossed == 0 || seen[acrossed])35 ans += dfs(m, n, v, depth + 1, seen, across);36 }37 38 seen[u] = false;39 return ans;40 }41};42