LintCode Q 909 - Android Unlock Patterns
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.
Example1Input: m = 1, n = 1 ; Output: 9
Example2Input: m = 1, n = 2 ; Output: 65
Solution : DFS / backtracking
Code:
public int numberOfPatterns(int m, int n) {
int[][] skip = new int[10][10];
skip[1][3] = skip[3][1] = 2;
skip[1][7] = skip[7][1] = 4;
skip[3][9] = skip[9][3] = 6;
skip[7][9] = skip[9][7] = 8;
skip[1][9] = skip[9][1] = skip[3][7] = skip[7][3] = skip[2][8] = skip[8][2] = skip[4][6] = skip[6][4] = 5;
boolean[] visited = new boolean[10];
int res = 0;
for (int i = m; i <= n; i++) {
res += DFS(visited, skip, 1, i - 1) * 4;
res += DFS(visited, skip, 2, i - 1) * 4;
res += DFS(visited, skip, 5, i - 1);
}
return res;
}
private int DFS(boolean visited[], int[][] skip, int cur, int remain) {
// boundary cases
if (remain < 0) return 0;
if (remain == 0) return 1;
//choose
visited[cur] = true;
//explore
int res = 0;
for (int i = 1; i <= 9; i++) {
if (!visited[i] && (skip[cur][i] == 0 || visited[skip[cur][i]]))
res += DFS(visited, skip, i, remain - 1);
}
//unchoose
visited[cur] = false;
return res;
}