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:
Given m = 1, n = 1, return 9.
Solution
public class Solution {
int ans = 0;
int m = 0;
int n = 0;
public int numberOfPatterns(int m, int n) {
this.m = m;
this.n = n;
boolean occupy[] = new boolean[10];
occupy[1] = true;
backtracking(4, occupy, 1, 1);
occupy[1] = false;
occupy[2] = true;
backtracking(4, occupy, 2, 1);
occupy[2] = false;
occupy[5] = true;
backtracking(1, occupy, 5, 1);
occupy[5] = false;
return ans;
}
public void backtracking(int bonus, boolean[] occupy, int last, int cnt) {
if(cnt >= m) ans += bonus; // we can start to count
if(cnt == n) return; // we need no more
for(int i = 1; i <= 9; i++) {
if(!occupy[i]) {
if( (last+i)%2 == 0 && !occupy[(last+i)/2]) { // possible cross
int mid = (last + i) / 2;
if(row(last) - row(mid) == row(mid) - row(i) && col(last) - col(mid) == col(mid) - col(i)) continue;
}
occupy[i] = true;
backtracking(bonus, occupy, i, cnt+1);
occupy[i] = false;
}
}
}
public int row(int i) {
return (i - 1)/3;
}
public int col(int i) {
return (i - 1)%3;
}
}