935. Knight Dialer

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.
 

Example 1:

Input: n = 1
Output: 10
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 = 3131
Output: 136006598
Explanation: Please take care of the mod.

Constraints:
  • 1 <= n <= 5000

From: LeetCode
Link: 935. Knight Dialer


Solution:

Ideas:
  • dp[d] = number of length-L numbers ending at digit d.

  • For each step, sum from all valid knight predecessors.

  • Digit 5 has no outgoing moves (stays valid only when n == 1).

  • Sum all digits at the end and return modulo 1e9+7.

Code:
int knightDialer(int n) {
    const int MOD = 1000000007;

    // Knight moves on the keypad (from digit -> list of next digits)
    const int nexts[10][3] = {
        {4,6,-1},   // 0 -> 4,6
        {6,8,-1},   // 1 -> 6,8
        {7,9,-1},   // 2 -> 7,9
        {4,8,-1},   // 3 -> 4,8
        {0,3,9},    // 4 -> 0,3,9
        {-1,-1,-1}, // 5 -> none
        {0,1,7},    // 6 -> 0,1,7
        {2,6,-1},   // 7 -> 2,6
        {1,3,-1},   // 8 -> 1,3
        {2,4,-1}    // 9 -> 2,4
    };

    long long dp[10], ndp[10];
    for (int d = 0; d < 10; ++d) dp[d] = 1;     // length 1: start anywhere

    for (int step = 2; step <= n; ++step) {
        for (int d = 0; d < 10; ++d) {
            long long ways = 0;
            for (int k = 0; k < 3; ++k) {
                int to = nexts[d][k];
                if (to == -1) break;
                ways += dp[to];
            }
            ndp[d] = ways % MOD;
        }
        for (int d = 0; d < 10; ++d) dp[d] = ndp[d];
    }

    long long ans = 0;
    for (int d = 0; d < 10; ++d) {
        ans += dp[d];
        if (ans >= MOD) ans -= MOD;
    }
    return (int)(ans % MOD);
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐