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.
Solution: DFS
BLOCK = [[0] * 10 for _ in xrange(10)]
BLOCK[1][3] = BLOCK[3][1] = 2
BLOCK[1][7] = BLOCK[7][1] = 4
BLOCK[9][3] = BLOCK[3][9] = 6
BLOCK[9][7] = BLOCK[7][9] = 8
BLOCK[1][9] = BLOCK[9][1] = 5
BLOCK[2][8] = BLOCK[8][2] = 5
BLOCK[3][7] = BLOCK[7][3] = 5
BLOCK[4][6] = BLOCK[6][4] = 5
class Solution(object):
def numberOfPatterns(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
patterns = 0
used = [False] * 10
for size in xrange(m, n + 1):
patterns += self.dfs(1, used, size) * 4
patterns += self.dfs(2, used, size) * 4
patterns += self.dfs(5, used, size)
return patterns
def dfs(self, num, used, size):
if size <= 0:
return 0
if size == 1:
return 1
patterns = 0
used[num] = True
for neighbor in self.neighbors(num, used):
patterns += self.dfs(neighbor, used, size - 1)
used[num] = False
return patterns
def neighbors(self, num, used):
for key in xrange(1, 10):
if not used[key]:
block = BLOCK[num][key]
if not block or used[block]:
yield key
Lessons:
- Because of symmetry, we only need to calculate the patterns start with
1,2and5. - For any given key, the number of its patterns equal to the sum of its neighbors's patterns.
- To find the current neighbors of a given key, take all unvisited keys. If an unvisited key is not blocked, it is a valid neighbor.