Skip to content

Commit 8a49979

Browse files
authored
Create Android Unlock Patterns.py
1 parent b1243f2 commit 8a49979

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Android Unlock Patterns.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'''
2+
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.
3+
4+
Rules for a valid pattern:
5+
6+
Each pattern must connect at least m keys and at most n keys.
7+
All the keys must be distinct.
8+
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.
9+
The order of keys used matters.
10+
11+
12+
13+
Explanation:
14+
15+
| 1 | 2 | 3 |
16+
| 4 | 5 | 6 |
17+
| 7 | 8 | 9 |
18+
Invalid move: 4 - 1 - 3 - 6
19+
Line 1 - 3 passes through key 2 which had not been selected in the pattern.
20+
21+
Invalid move: 4 - 1 - 9 - 2
22+
Line 1 - 9 passes through key 5 which had not been selected in the pattern.
23+
24+
Valid move: 2 - 4 - 1 - 3 - 6
25+
Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
26+
27+
Valid move: 6 - 5 - 4 - 1 - 9 - 2
28+
Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
29+
30+
Example:
31+
32+
Input: m = 1, n = 1
33+
Output: 9
34+
'''
35+
36+
class Solution(object):
37+
def numberOfPatterns(self, m, n):
38+
"""
39+
:type m: int
40+
:type n: int
41+
:rtype: int
42+
"""
43+
dic = {(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, (9, 1):5, (2, 8):5, (8, 2):5, (3, 7):5, (7, 3):5, (4, 6):5, (6, 4):5}
44+
45+
res = 0
46+
for step in xrange(m, n+1):
47+
res += 4 * self.find(1, step-1, dic, set())
48+
res += 4 * self.find(2, step-1, dic, set())
49+
res += self.find(5, step-1, dic, set())
50+
return res
51+
52+
def find(self, x, step, dic, visited):
53+
if step == 0:
54+
return 1
55+
visited.add(x)
56+
res = 0
57+
for y in xrange(1, 10):
58+
if y not in visited and ((x, y) not in dic or dic[(x, y)] in visited):
59+
res += self.find(y, step-1, dic, visited)
60+
61+
visited.remove(x)
62+
return res
63+
64+
65+

0 commit comments

Comments
 (0)