[LeetCode] Knight Dialer

935. Knight Dialer

The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:

A chess knight can move as indicated in the chess diagram below:

We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).

Given an integer n, return how many distinct phone numbers of length n we can dial.

You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.

As the answer may be very large, return the answer modulo 109 + 7.

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
#define MOD 1000000007
class Solution {
vector<vector<int>> reachAble{
{4, 6}, //0
{6, 8}, //1
{7, 9}, //2
{4, 8}, //3
{3, 9, 0}, //4
{}, //5
{1, 7, 0}, //6
{2, 6}, //7
{1, 3}, //8
{2, 4} //9
};
public:
int knightDialer(int n) {
vector<int> res(10, 1), tmp(10);
while(--n) {
for (int i = 0; i < 10; ++i) {
tmp[i] = accumulate(begin(reachAble[i]), end(reachAble[i]), 0, [&](int origin, int from) {return (origin + res[from]) % MOD;});
}
res = tmp;
}

return accumulate(begin(res), end(res), 0, [](int origin, int n) {return (origin + n) % MOD;});
}
};
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
class Solution {
vector<vector<int>> reachAble {
{4, 6}, //0
{6, 8}, //1
{7, 9}, //2
{4, 8}, //3
{3, 9, 0}, //4
{}, //5
{1, 7, 0}, //6
{2, 6}, //7
{1, 3}, //8
{2, 4} //9
};
vector<vector<int>> m;
int MOD = 1e9 + 7;

int move(int n, int dial) {
if(n == 0) return 1;
if(m[n][dial] != -1) return m[n][dial];
m[n][dial] = 0;
for(auto to : reachAble[dial]) {
m[n][dial] = (m[n][dial] + move(n - 1, to)) % MOD;
}
return m[n][dial];
}
public:
int knightDialer(int n) {
m = vector<vector<int>>(n, vector<int>(10, -1));
int res = 0;
for(int i = 0; i < 10; i++) {
res = (res + move(n - 1, i)) % MOD;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/26/PS/LeetCode/knight-dialer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.