351. Android Unlock Patterns
阿新 • • 發佈:2018-11-09
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: 1. Each pattern must connect at least m keys and at most n keys.2. All the keys must be distinct. 3. 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. 4. 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 峰哥的那道題 Return all The trick is , 對稱性 Similar to return all n queens class Solution { public int numberOfPatterns(int m, int n) { int res = 0; boolean[] visited = new boolean[10]; int[][] jumps = new int[10][10]; jumps[1][3] = jumps[3][1] = 2; jumps[7][9] = jumps[9][7] = 8; jumps[1][7] = jumps[7][1] = 4; jumps[3][9] = jumps[9][3] = 6; jumps[4][6] = jumps[6][4] = jumps[2][8] = jumps[8][2] = jumps[1][9] = jumps[9][1] = jumps[3][7] = jumps[7][3] = 5; res += dfs(1, 1, m, n, jumps, visited) * 4; // 1, 3, 7, 9 symmetric res += dfs(2, 1, m, n, jumps, visited) * 4; // 2, 4, 6, 8 symmetric res += dfs(5, 1, m, n, jumps, visited); // 5 return res; } private int dfs(int num, int len, int m, int n, int[][] jumps, boolean[] visited){ int res = 0; if(len >= m && len <= n) res++; if(len > n) return 0; // bug 1 : not just return; because this dfs return value is int visited[num] = true; // for(int i = 1; i <= 9; i++){ int jump = jumps[num][i]; // skip if this number is already visited, // skip if the number crossed between num and i is not visited and // it's not 0 if(!visited[i] && (jump == 0 || visited[jump])){ res += dfs(i, len + 1, m, n, jumps, visited); } } visited[num] = false; // what's this backtracking for return res; } } // i feel this backtracking is for two things // one thing is that recover the boolean[] visited from path starting with 1 // for the path starting with 2 , same as recover from path starting at 2 for // path starting at 5 // this backtracking also does things inside the path starting from 1 // for example : 1 2 3... is a path, 1 3 2 ... is another path. // so in order to cover all the cases, recover the boolean[] as soon as you // finish one dfs