Difficulty: Medium

Related Topics: Dynamic Programming

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:

935. Knight Dialer - 图1

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).

935. Knight Dialer - 图2

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 10 + 7.

Example 1:

  1. Input: n = 1
  2. Output: 10
  3. Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.

Example 2:

Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]

Example 3:

Input: n = 3
Output: 46

Example 4:

Input: n = 4
Output: 104

Example 5:

Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.

Constraints:

  • 1 <= n <= 5000

Solution

Language: Java

class Solution {
    private static int[][] moves = {{1, 2}, {-1, 2}, {-1, -2}, {1, -2},
                                    {2, 1}, {2, -1}, {-2, -1}, {-2, 1}};

    private static int mod = 1000000007;

    private Integer[][][] memo;

    public int knightDialer(int n) {
        memo = new Integer[n + 1][4][3];

        // 一开始可以从 0 ~ 9 每个数字都试一次
        int ans = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 3; j++) {
                ans += dp(n, i, j);
                ans %= mod;
            }
        }

        return ans;
    }

    // 定义:knight 从 (i, j) 开始踏步,形成 n 位数的方法数有
    private int dp(int n, int i, int j) {
        // 出口
        // 1. 越界,无解
        if(i < 0 || i >= 4 || j < 0 || j >= 3) return 0;
        // 2. 非法格子(* #),无解
        if(i == 3 && j != 1) return 0;
        // 3. 踩一位数,只有一种方法数
        if(n == 1) return 1;

        if(memo[n][i][j] != null) return memo[n][i][j];

        int ans = 0;

        // knight 每次可以移动 8 步
        for (int[] move : moves) {
            ans += dp(n - 1, i + move[0], j + move[1]);
            ans %= mod;
        }

        return memo[n][i][j] = ans;
    }
}