351. Android Unlock Patterns
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |Input: m = 1, n = 1
Output: 9Last updated
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |Input: m = 1, n = 1
Output: 9Last updated
int DFS(short visited, const vector<vector<int> >& check, int cur, int rem) {
if (rem == 0) return 1;
visited |= (1 << cur);
int res = 0;
for (int num = 1; num <= 9; ++num) {
if (((visited & (1 << num) ) == 0) &&
(check[cur][num] == 0 || (visited & (1 << check[cur][num]) ) ) )
res += DFS(visited, check, num, rem - 1);
}
visited ^= (1 << cur);
return res;
}
int numberOfPatterns(int m, int n) {
vector<vector<int> > check(10, vector<int>(10, 0));
// Build check relations
check[1][3] = check[3][1] = 2;
check[4][6] = check[6][4] = 5;
check[7][9] = check[9][7] = 8;
check[1][7] = check[7][1] = 4;
check[2][8] = check[8][2] = 5;
check[3][9] = check[9][3] = 6;
check[1][9] = check[9][1] = check[3][7] = check[7][3] = 5;
short visited = 0;
unordered_map<short, int> memo;
int res = 0;
for (int i = m; i <= n; ++i) {
res += DFS(visited, check, 1, i - 1) * 4;
res += DFS(visited, check, 2, i - 1) * 4;
res += DFS(visited, check, 5, i - 1);
}
return res;
}