LintCode 1707 · Knight Dialer (DP)

71 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

原文链接:blog.csdn.net/roufoo/arti…

1707 · Knight Dialer

Algorithms

Medium

image.png Accepted Rate44%

Description

Solution

Notes

Discuss

Leaderboard

Description

A chess knight can move as indicated in the chess diagram below:

image.png

image.png

This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. Each hop must be from one key to another numbered key.

Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N digits total.

How many distinct numbers can you dial in this manner?

Since the answer may be large, output the answer modulo 10^9 + 7.

1 \leq N \leq 50001≤N≤5000

Example

Example 1:

Input: 1 Output: 10 Explanation: The answer may be 0, 1, 2, 3, ..., 9. Example 2:

Input: 2 Output: 20 Explanation: The answer may be 04, 06, 16, 18, 27, 29, 34, 38, 43, 49, 40, 61, 67, 60, 72, 76, 81, 83, 94, 92. Example 3:

Input: 3 Output: 46 Tags

Company

FacebookDropboxMicrosoftGoogle

解法1:DP。 dp[i][j]表示第i次跳到数字j时的distinct number数。 注意:

  1. 1e+9之类的科学计数法默认是double。但如果我们定义成int M = 1e+9则可将其强转为int。注意1e+9仍在int范围内。
  2. dp[1][i]初始化为1, 不是i。因为每个数字只能算一种情况。
  3. unordered_set可以直接用vector<vector>代替,因为序号0..9都是按顺序来的,可以当数组的索引。
class Solution {
public:
    /**
     * @param N: N
     * @return: return the number of distinct numbers can you dial in this manner mod 1e9+7
     */
    int knightDialer(int N) {
        //#define M (long long)(10e9 + 7)
        int M = 1e9 + 7;
        unordered_map<int, vector<int>> dict = 
        { {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}}   
        };
 
        vector<vector<int>> dp(N + 1, vector<int>(10, 0));
        for (int i = 0; i <= 9; i++) {
            dp[1][i] = 1;
        }
        
        for (int i = 2; i <= N; i++) {
            for (int j = 0; j <= 9; j++) {
                for (int k = 0; k < dict[j].size(); k++) {
                    dp[i][j] = (dp[i][j] + dp[i - 1][dict[j][k]]) % M;
                }
            }
        }
        int sum = 0;
        for (int i = 0; i <= 9; ++i) {
            sum = (sum + dp[N][i]) % M;
        }
        return sum;
    }
};