-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path351. Android Unlock Patterns.c
104 lines (76 loc) · 2.52 KB
/
351. Android Unlock Patterns.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
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.
Credits:Special thanks to @elmirap for adding this problem and creating all test cases.
*/
#define PRINT_START() do { } while (0)
#define PRINT_SEQ() do { } while (0)
#define PRINT_NL() do { } while (0)
int map[10][10] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/*0*/{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
/*1*/{ 0, 0, 0, 2, 0, 0, 0, 4, 0, 5},
/*2*/{ 0, 0, 0, 0, 0, 0, 0, 0, 5, 0},
/*3*/{ 0, 2, 0, 0, 0, 0, 0, 5, 0, 6},
/*4*/{ 0, 0, 0, 0, 0, 0, 5, 0, 0, 0},
/*5*/{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
/*6*/{ 0, 0, 0, 0, 5, 0, 0, 0, 0, 0},
/*7*/{ 0, 4, 0, 5, 0, 0, 0, 0, 0, 8},
/*8*/{ 0, 0, 5, 0, 0, 0, 0, 0, 0, 0},
/*9*/{ 0, 5, 0, 6, 0, 0, 0, 8, 0, 0}
};
void pattern(int x, int d, int *k, int *visited) {
int i;
if (d == 0) {
PRINT_NL();
(*k) ++;
return;
}
for (i = 1; i < 10; i ++) {
if (!visited[i] && visited[map[x][i]]) {
visited[i] = 1;
PRINT_SEQ();
pattern(i, d - 1, k, visited);
visited[i] = 0;
}
}
}
int numberOfPatterns(int m, int n) {
int visited[10] = { 0 };
int d, x, t, k;
visited[0] = 1;
t = 0;
for (d = m; d <= n; d ++) {
PRINT_START();
k = 0;
pattern(0, d, &k, visited);
t += k;
}
return t;
}
/*
Difficulty:Medium
Total Accepted:14.3K
Total Submissions:32.7K
Companies Google
Related Topics Dynamic Programming Backtracking
*/