LeetCode 351. Android Unlock Patterns

Description

https://leetcode.com/problems/android-unlock-patterns/

Given an Android 3×3 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

Python Solution

Create a map indicating the mid keys can be skipped. Use the depth-first search to find all possible sequences.

skip_map = {
    (1, 3): 2, 
    (3, 1): 2, 
    (1, 7): 4, 
    (7, 1): 4, 
    (3, 9): 6, 
    (9, 3): 6, 
    (7, 9): 8,
    (9, 7): 8,    
    (1, 9): 5,
    (2, 8): 5,
    (3, 7): 5,
    (4, 6): 5,
    (6, 4): 5,
    (7, 3): 5,
    (8, 2): 5,
    (9, 1): 5
}

class Solution:
    def numberOfPatterns(self, m: int, n: int) -> int:
        
        sequence = []
        visited = set()
        
        results = []
        
        self.dfs(sequence, visited, results, m, n)
    
        return len(results)

    def dfs(self, sequence, visited, results, m, n):
        if m <= len(sequence) <= n:
            results.append(len(sequence))
            
        if len(sequence) > n:
            return
        
        for i in range(1, 10):
            if i in visited:
                continue
            
            if sequence:           
                pair = (sequence[-1], i)            
                mid = (sequence[-1] + i) // 2

                if pair in skip_map and mid == skip_map[pair] and mid not in visited:
                    continue
                                
            sequence.append(i)
            visited.add(i)
            
            self.dfs(sequence, visited, results, m, n)
            
            sequence.pop()
            visited.remove(i)
  • Time Complexity: ~N!
  • Space Complexity: ~N

Leave a Reply

Your email address will not be published. Required fields are marked *