leetcode - 935. Knight Dialer

Description

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:
在这里插入图片描述

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 10^9 + 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

Solution

Dynamic programming, let f(x, n) denote how many distinct numbers with x as the start and n numbers, then we have: f(x, n) = f(a, n - 1) + f(b, n - 1), where a and b are other numbers that the knight could jump.

The number map is as below:

number_map = {
    1: (6, 8),
    2: (7, 9),
    3: (4, 8), 
    4: (3, 9, 0),
    5: (),
    6: (1, 7, 0),
    7: (2, 6), 
    8: (1, 3),
    9: (2, 4),
    0: (4, 6)
}

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

Code

class Solution:
    def knightDialer(self, n: int) -> int:
        memo = {(i, 1): 1 for i in range(10)}
        number_map = {
            1: (6, 8),
            2: (7, 9),
            3: (4, 8), 
            4: (3, 9, 0),
            5: (),
            6: (1, 7, 0),
            7: (2, 6), 
            8: (1, 3),
            9: (2, 4),
            0: (4, 6)
        }
        for k in range(2, n + 1):
            for i in range(10):
                memo[(i, k)] = 0
                for next_position in number_map[i]:
                    memo[(i, k)] += memo[(next_position, k - 1)]
                    memo[(i, k)] %= 1000000007
        return sum(memo[(i, n)] for i in range(10)) % 1000000007
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值