Skip to main content
Back to problems
#935
Medium Algorithms

Knight dialer

Dynamic Programming
61.7% acceptance
Feb 25, 2026
3198
452
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 diagram: 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.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn knight_dialer(n: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    // knight moves from each digit
    let moves: Vec<Vec<usize>> = vec![
      vec![4, 6],    // 0
      vec![6, 8],    // 1
      vec![7, 9],    // 2
      vec![4, 8],    // 3
      vec![0, 3, 9], // 4
      vec![],        // 5
      vec![0, 1, 7], // 6
      vec![2, 6],    // 7
      vec![1, 3],    // 8
      vec![2, 4],    // 9
    ];
    let mut dp = vec![1i64; 10];
    for _ in 1..n {
      let mut ndp = vec![0i64; 10];
      for d in 0..10 {
        for &next in &moves[d] {
          ndp[next] = (ndp[next] + dp[d]) % MOD;
        }
      }
      dp = ndp;
    }
    (dp.iter().sum::<i64>() % MOD) as i32
  }
}