-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path935. Knight Dialer.c
125 lines (81 loc) · 2.09 KB
/
935. Knight Dialer.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
935. Knight Dialer
A chess knight can move as indicated in the chess diagram below:
.
This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. Each hop must be from one key to another numbered key.
Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N digits total.
How many distinct numbers can you dial in this manner?
Since the answer may be large, output the answer modulo 10^9 + 7.
Example 1:
Input: 1
Output: 10
Example 2:
Input: 2
Output: 20
Example 3:
Input: 3
Output: 46
Note:
1 <= N <= 5000
*/
#define MOD 1000000007
const int map[][4] = {
/* 0 */ { 4, 6, -1 },
/* 1 */ { 6, 8, -1 },
/* 2 */ { 7, 9, -1 },
/* 3 */ { 4, 8, -1 },
/* 4 */ { 3, 9, 0, -1 },
/* 5 */ { -1 },
/* 6 */ { 1, 7, 0, -1 },
/* 7 */ { 2, 6, -1 },
/* 8 */ { 1, 3, -1 },
/* 9 */ { 2, 4, -1 }
};
/* simple back tracking, need to add memorization to pass TLE */
#if 0
int helper(int p, int n) {
int *m, s, steps = 0;
if (n == 0) return 1;
if (p == 5) return -1;
m = map[p];
while (*m != -1) {
s = helper(*m, n - 1);
if (s > 0) steps += s;
m ++;
}
return steps;
}
#endif
int knightDialer(int N) {
int buff[20] = { 0 };
int *p, *n, *t, i, k = 0;
p = buff;
n = &buff[10];
p[0] = p[1] = p[2] = p[3] = p[4] =
p[5] = p[6] = p[7] = p[8] = p[9] = 1;
if (N > 1) p[5] = 0;
while (N -- > 1) {
n[0] = (p[4] + p[6]) % MOD;
n[1] = (p[6] + p[8]) % MOD;
n[2] = (p[7] + p[9]) % MOD;
n[3] = (p[4] + p[8]) % MOD;
n[4] = ((p[3] + p[9]) % MOD + p[0]) % MOD;
n[6] = ((p[1] + p[7]) % MOD + p[0]) % MOD;
n[7] = (p[2] + p[6]) % MOD;
n[8] = (p[1] + p[3]) % MOD;
n[9] = (p[2] + p[4]) % MOD;
t = p;
p = n;
n = t;
}
for (i = 0; i < 10; i ++) {
k = (k + p[i]) % MOD;
}
return k;
}
/*
Difficulty:Medium
*/