Leetcode 935 Knight Dialer

HowieLee59發表於2018-11-04

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

 .           

 

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 digits N total.

How many distinct numbers can you dial in this manner?

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

Example 1:

Input: 1
Output: 10

Example 2:

Input: 2
Output: 20

Example 3:

Input: 3
Output: 46

Note:

  • 1 <= N <= 5000

這個題的意思是根據一個騎士的遊歷表,輸入的是要產生的電話位數,使用dp來解即可。

1)

class Solution {
    const int MOD = 1e9+7;
    int add(int a, int b) { return (a + b) % MOD; }
public:
    int knightDialer(int N) {
        int dp[5111][10];
        for(int i=0;i<10;i++) dp[0][i] = 1;
        for(int t=1;t<N;t++) {
            dp[t][0] = add(dp[t-1][4], dp[t-1][6]);
            dp[t][1] = add(dp[t-1][6], dp[t-1][8]);
            dp[t][2] = add(dp[t-1][7], dp[t-1][9]);
            dp[t][3] = add(dp[t-1][4], dp[t-1][8]);
            dp[t][4] = add(dp[t-1][0], add(dp[t-1][9], dp[t-1][3]));
            dp[t][5] = 0;
            dp[t][6] = add(dp[t-1][1], add(dp[t-1][7], dp[t-1][0]));
            dp[t][7] = add(dp[t-1][2], dp[t-1][6]);
            dp[t][8] = add(dp[t-1][1], dp[t-1][3]);
            dp[t][9] = add(dp[t-1][2], dp[t-1][4]);
        }
        
        int ans = 0;
        for(int i=0;i<10;i++) ans = add(ans, dp[N-1][i]);
        return ans;
    }
};

2)

    public static final int MOD = 1000000007;
    public int knightDialer(int N) {
        int[][] graph = new int[][]{{4,6},{6,8},{7,9},{4,8},{3,9,0},{},{1,7,0},{2,6},{1,3},{2,4}};
        int cnt = 0;
        Integer[][] memo = new Integer[N+1][10];
        for (int i = 0; i <= 9; i++)
            cnt = (cnt + helper(N-1, i, graph, memo)) % MOD;
        return cnt;
    }
    private int helper(int N, int cur, int[][] graph, Integer[][] memo) {
        if (N == 0)
            return 1;
        if (memo[N][cur] != null)
            return memo[N][cur];
        int cnt = 0;
        for (int nei : graph[cur])
            cnt = (cnt + helper(N-1, nei, graph, memo)) % MOD;
        memo[N][cur] = cnt;
        return cnt;
    }

 

相關文章