Skip to problem
←

Knight Dialer

Medium 0 attempts

Count the distinct digit sequences of length n that a chess knight can dial on this keypad:

text
1 2 3
4 5 6
7 8 9
  0

Start on any digit. Each jump moves two cells in one direction and one cell perpendicular to it, landing only on a digit. The two blank bottom corners are unavailable.

Include the starting digit, so a sequence of length n uses exactly n - 1 jumps. Leading zeros and revisiting digits are allowed. For example, 04 and 40 are different valid sequences of length 2. Digit 5 has no legal moves, but still counts when n = 1. Return the count modulo 1000000007.

Function contract

n is the length of the digit sequence, including the starting digit.

Output: Return the number of distinct length-n digit sequences modulo 1000000007. Leading zeros are allowed.

Example 1

Input
n = 1
Output
10

Explanation: No jumps are needed. Each starting digit, including 0 and 5, gives one sequence.

Example 2

Input
n = 2
Output
20
Constraints
  • 1 <= n <= 5000

Approach: DP with Adjacency Map

Define the valid knight moves for each digit. For each step, accumulate the count of ways to reach each digit from its valid predecessor digits. Use a DP array that is updated iteratively.

javascript
function knightDialer(n) {
  const MOD = 1e9 + 7;
  const moves = {
    0: [4, 6],
    1: [6, 8],
    2: [7, 9],
    3: [4, 8],
    4: [0, 3, 9],
    5: [],
    6: [0, 1, 7],
    7: [2, 6],
    8: [1, 3],
    9: [2, 4],
  };
  let dp = new Array(10).fill(1);
  for (let i = 1; i < n; i++) {
    const next = new Array(10).fill(0);
    for (let d = 0; d <= 9; d++)
      for (const m of moves[d]) next[d] = (next[d] + dp[m]) % MOD;
    dp = next;
  }
  return dp.reduce((a, b) => (a + b) % MOD, 0);
}

Time Complexity: O(n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript