Problem Name: 935. Knight Dialer
Problem Link: https://leetcode.com/problems/knight-dialer/?envType=daily-question&envId=2023-11-27
Difficulty: Medium
Tag: Dynamic Programming
Language: C# | C++
OJ: LeetCode
Algorithm
The algorithm behind the problem:
- Initialize an array array representing the number of ways to reach each digit from the starting digit in one move.
- Initialize a temporary array temp to store intermediate results.
- Use a loop to iterate n-1 times to simulate the knight's moves for each step.
- Update the temp array based on the possible moves from each digit.
- Copy the values from the temp array back to the array array.
- Calculate the sum of all values in the array array, taking the modulo 1000000007.
- Return the result as an integer.
Code(C#)
public class Solution
{
public int KnightDialer(int n)
{
long[] array = new long[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
long[] temp = new long[10];
long mod = 1000000007;
long sum = 0;
for(int i=1; i<n; i++)
{
temp[0] = (array[4] + array[6]) % mod;
temp[1] = (array[6] + array[8]) % mod;
temp[2] = (array[7] + array[9]) % mod;
temp[3] = (array[4] + array[8]) % mod;
temp[4] = (array[3] + array[9] + array[0]) % mod;
temp[6] = (array[1] + array[7] + array[0]) % mod;
temp[7] = (array[2] + array[6]) % mod;
temp[8] = (array[1] + array[3]) % mod;
temp[9] = (array[2] + array[4]) % mod;
Buffer.BlockCopy(temp, 0, array, 0, temp.Length * sizeof(long));
}
for (int i = 0; i < array.Length; i++)
sum += (array[i] % mod);
return (int)(sum%mod);
}
}
Code(C++)
class Solution {
public:
int knightDialer(int n) {
vector<long> array = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
vector<long> temp(10);
long mod = 1000000007;
long sum = 0;
for (int i = 1; i < n; i++) {
temp[0] = (array[4] + array[6]) % mod;
temp[1] = (array[6] + array[8]) % mod;
temp[2] = (array[7] + array[9]) % mod;
temp[3] = (array[4] + array[8]) % mod;
temp[4] = (array[3] + array[9] + array[0]) % mod;
temp[6] = (array[1] + array[7] + array[0]) % mod;
temp[7] = (array[2] + array[6]) % mod;
temp[8] = (array[1] + array[3]) % mod;
temp[9] = (array[2] + array[4]) % mod;
for(int j=0; j<10; j++)
array[j]=temp[j];
}
for (int i = 0; i < array.size(); i++)
sum += (array[i] % mod);
return (int)(sum % mod);
}
};