Leetcode 935 Knight Dialer

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;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值