935. Knight Dialer
https://leetcode.com/problems/knight-dialer/
Last updated
https://leetcode.com/problems/knight-dialer/
Last updated
/*
* @lc app=leetcode id=935 lang=cpp
*
* [935] Knight Dialer
*/
// @lc code=start
class Solution {
public:
int knightDialer(int N) {
const unsigned int M = 1000000007;
unordered_map<int, vector<int>> hops{{0, {4, 6}}, {1, {6, 8}},
{2, {7, 9}}, {3, {4, 8}}, {4, {3, 9, 0}},
{6, {7, 1, 0}}, {7, {2, 6}}, {8, {1, 3}}, {9, {2, 4}}};
vector<vector<int>> dp(2, vector<int>(10, 0));
for (int i = 0; i <= 9; ++i) {
dp[0][i] = 1;
}
for (int i = 1; i < N; ++i) {
for (int j = 0; j <= 9; ++j) dp[i % 2][j] = 0;
for (int j = 0; j <= 9; ++j) {
for (const auto p : hops[j]) {
dp[i % 2][j] += dp[(i - 1) % 2][p];
dp[i % 2][j] %= M;
}
}
}
int res = 0;
for (int i = 0; i <= 9; ++i) {
res += dp[(N - 1) % 2][i];
res %= M;
}
return res;
}
};
// @lc code=end