Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
Each pattern must connect at least m keys and at most n keys. All the keys must be distinct. If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed. The order of keys used matters.
Explanation:
| 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 | Invalid move: 4 - 1 - 3 - 6 Line 1 - 3 passes through key 2 which had not been selected in the pattern.
Invalid move: 4 - 1 - 9 - 2 Line 1 - 9 passes through key 5 which had not been selected in the pattern.
Valid move: 2 - 4 - 1 - 3 - 6 Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
Valid move: 6 - 5 - 4 - 1 - 9 - 2 Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
Example:
Input: m = 1, n = 1 Output: 9
// 36ms, 63%
class Solution {
private:
bool moveOk(int lastKey, int i, bitset<10>& used) {
// first touch
if (lastKey < 0)
return true;
// key already used
if (used.test(i))
return false;
// adjacent keys, or knigh jump
if ((lastKey + i) % 2 == 1)
return true;
// jump over one key diagonally, like 1 to 9, 2 to 8
int mid = (lastKey + i) / 2;
if (mid == 5)
return used.test(mid);
// adjacent keys on diagonal except the longest diagonal as already checked the longest one above
if (((i-1)%3 != (lastKey-1)%3) && ((i-1)/3 != (lastKey-1)/3))
return true;
// all other jumps
return used.test(mid);
}
int calcMoves(int lastKey, bitset<10>& used, int len) {
if (len == 0)
return 1;
int res = 0;
for (int i = 1; i <= 9; i++) {
if (moveOk(lastKey, i, used)) {
used.set(i);
res += calcMoves(i, used, len - 1);
used.reset(i);
}
}
return res;
}
public:
int numberOfPatterns(int m, int n) {
int res = 0;
bitset<10> used;
used.reset();
for (int len = m; len <= n; len++) {
res += calcMoves(-1, used, len);
used.reset();
}
return res;
}
};