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.
Using dfs to solve this problem, Something to know.
for the array
0 1 2
3 4 5
6 7 8.
since 0 2 6 8 are symmetric and 1 3 5 7 are symmetric, we only need to dfs one of them.
How can we know if we can go from i to j.
if i or j is 4 return true;
any odd can go to any even and vice versa.
for even number 0 2 6 8, they can go to another iff (i + j) / 2 is visited.
for even number 1 3 5 7, we need to check 17 and 35, the sum of them is 8 and they can go to another iff 4 is vistied.
Code:
public class Solution {
public int numberOfPatterns(int m, int n) {
int ans = 0;
for(int i = m; i <= n; i++){
ans += 4 * dfs(new boolean[9],i,0);
ans += 4 * dfs(new boolean[9],i,1);
ans += dfs(new boolean[9],i,4);
}
return ans;
}
int dfs(boolean[] visited, int count, int cur){
if(count == 1) {
return 1;
}
int ret = 0;
visited[cur] = true;
for(int i = 0; i < 9; i++){
if(!canGo(cur,i,visited)) continue;
ret += dfs(visited,count-1,i);
}
visited[cur] = false;
return ret;
}
boolean canGo(int from, int to, boolean[] visited){
if(visited[to]) return false;
if(from == 4 || to == 4) return true;
else if(from % 2 != to % 2) return true;
else if(from % 2 == 0) return visited[(from + to) / 2];
else if(from + to == 8) return visited[4];
else return true;
}
}