Problem Description
Given a 3x3 grid representing the Android lock screen, count the number of valid unlock patterns that use at least m keys and at most n keys. A valid pattern must use distinct dots and if a line drawn between two consecutive dots passes through another dot, that intervening dot must have already been used in the pattern. Patterns are considered unique if the set or the order of the dots used differ.
Key Insights
- Leverage symmetry: The grid’s corners, edges, and center exhibit symmetry which allows us to compute results for one cell in each symmetric group and then multiply appropriately.
- Use DFS (depth-first search) with backtracking to explore all possible patterns.
- Precompute a “skip” table that records the dot between two given dots if a jump is required. This table helps quickly decide if a move is valid—i.e., if the intervening dot is already visited.
- Ensure that during the DFS recursion, a move is only allowed if it doesn’t violate the rule of "jumping" over a non-visited dot.
- Use the constraints on m and n to count patterns of valid lengths.
Space and Time Complexity
Time Complexity: O(9!) in the worst-case scenario since we explore all possible permutations of the 9 dots. However, due to symmetry and early pruning with the skip condition, the practical runtime is considerably lower. Space Complexity: O(9) due to the recursion stack and space for tracking visited nodes.
Solution
The solution uses a DFS algorithm with backtracking. A 10-element visited boolean array (using 1-indexing for clarity) keeps track of which dots have been used. A precomputed 2D array (skip table) holds the intermediate dot that must be visited when moving between two dots, if any. The DFS starts from a given dot and recursively attempts to extend the pattern by moving to every possible other dot that meets the conditions (either no intervening dot or the intervening dot has been visited). By using symmetry, we compute the count for one corner, one edge, and the center, then aggregate the result appropriately.