Question

Formatted question description: https://leetcode.ca/all/351.html

 351	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.

 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.

 @tag-dp

Algorithm

Let’s take a look at what is illegal,

  • First, 1 cannot go directly to 3, it must go through 2.
  • For the same reason, there are 4 to 6, 7 to 9, 1 to 7, 2 to 8, 3 to 9,
  • There are also diagonals that must pass through 5, such as 1 to 9, 3 to 7, etc.

Create a two-dimensional array jumps to record whether there is an intermediate key between the two number keys,

Then use a one-bit array visited to record whether a key has been visited.

Then use recursion to solve. First call the recursive function for 1, in the recursive function, traverse each number from 1 to 9 next, and then find if there is a jump between them.

If next has not been visited, and jump is 0. Or jump has been visited. Call the recursive function to next.

  • After the number of patterns of number 1 is calculated, since 1,3,7,9 are symmetrical, multiply by 4
  • Then call the recursive function on the number 2.
    • 2, 4, 6, 9 are also symmetrical, and then multiply by 4.
  • Finally, call 5 separately, and then add up all of them to get the final result.

Code

Java

  • 
    public class Android_Unlock_Patterns {
    
        public class Solution_4multiply {
    
            public int numberOfPatterns(int m, int n) {
                int res = 0;
                boolean[] visited = new boolean[10];
                int[][] jumps = new int[10][10]; // record whether there is an intermediate key between the two number keys
                jumps[1][3] = jumps[3][1] = 2;
                jumps[4][6] = jumps[6][4] = 5;
                jumps[7][9] = jumps[9][7] = 8;
                jumps[1][7] = jumps[7][1] = 4;
                jumps[2][8] = jumps[8][2] = 5;
                jumps[3][9] = jumps[9][3] = 6;
                jumps[1][9] = jumps[9][1] = jumps[3][7] = jumps[7][3] = 5;
                res += dfs(1, 1, m, n, jumps, visited, 0) * 4;
                res += dfs(2, 1, m, n, jumps, visited, 0) * 4;
                res += dfs(5, 1, m, n, jumps, visited, 0);
                return res;
            }
    
            int dfs(int num, int len, int m, int n, int[][] jumps, boolean[] visited, int res) {
                if (len >= m) ++res;
                ++len;
                if (len > n) return res;
                visited[num] = true;
                for (int next = 1; next <= 9; ++next) {
                    int jump = jumps[num][next];
                    if (!visited[next] && (jump == 0 || visited[jump])) {
                        res = dfs(next, len, m, n, jumps, visited, res);
                    }
                }
                visited[num] = false;
                return res;
            }
        }
    
    
        // below is dfs to check every possible, with no multiplied-4 optimization
        public class Solution {
    
            private int patterns;
    
            public int numberOfPatterns(int m, int n) {
    
                boolean[] isVisited = new boolean[10];
    
                for (int i = 1; i <= 9; i++) {
                    isVisited[i] = true;
                    find(isVisited, i, 1, m, n);
                    isVisited[i] = false;
                }
    
                return patterns;
            }
    
            private void find(boolean[] isVisited, int from, int currentStep, int m, int n) {
                if (currentStep == n) {
                    patterns++;
                    return;
                }
                if (currentStep >= m) {
                    patterns++;
                }
    
                for (int i = 1; i <= 9; i++) {
                    if (isValid(isVisited, from, i)) {
                        isVisited[i] = true;
                        find(isVisited, i, currentStep + 1, m, n);
                        isVisited[i] = false;
                    }
                }
            }
    
            // core is this function, for check logic
            private boolean isValid(boolean[] isVisited, int from, int to) {
                if (from == to) {
                    return false;
                }
    
                int i = Math.min(from, to);
                int j = Math.max(from, to);
    
                if ((i == 1 && j == 9) || (i == 3 && j == 7)) {
                    return isVisited[5] && !isVisited[to];
                }
                if ((i == 1 || i == 4 || i == 7) && i + 2 == j) {
                    return isVisited[i + 1] && !isVisited[to];
                }
                if (i <= 3 && i + 6 == j) {
                    return isVisited[i + 3] && !isVisited[to];
                }
    
                return !isVisited[to];
            }
        }
    }
    
  • Todo
    
  • class Solution(object):
      def numberOfPatterns(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
    
        def dfs(m, n, prev, visited, length):
          if m <= length <= n:
            self.ans += 1
    
          if length == n:
            return
    
          for i in range(1, 10):
            if i not in visited:
              x, y, xp, yp = (i - 1) / 3, (i - 1) % 3, (prev - 1) / 3, (prev - 1) % 3
              if (5 not in visited and (x + xp, y + yp) == (2, 2)) or (
                (x == xp and abs(y - yp) == 2) or (y == yp and abs(x - xp) == 2)) and (prev + i) / 2 not in visited:
                continue
              visited |= {i}
              dfs(m, n, i, visited, length + 1)
              visited.discard(i)
    
        visited = set()
        self.ans = 0
        dfs(m, n, -99, visited, 0)
        return self.ans
    
    

All Problems

All Solutions