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 modulo10⁹ + 7.
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.
defprod(a: list[list[int]], b: list[list[int]]) -> list[list[int]]: # `a` is an m*k matrix, `b` is a k*n matrix. # Returns a m*n matrix which is a x b. m = len(a) k = len(b) n = len(b[0]) res = [[sum(a[r][i] * b[i][c] for i inrange(k)) % MOD for c inrange(n)] for r inrange(m)] return res
classSolution: defknightDialer(self, n: int) -> int: if n == 1: return10
n -= 1 mask = 1 n1 = n while n1 := n1 >> 1: mask <<= 1
m = [[0, 1, 1, 0], [2, 0, 0, 0], [2, 0, 0, 1], [0, 0, 2, 0]] res = m while mask := mask >> 1: res = prod(res, res) if n & mask: res = prod(res, m)
m0 = [[1], [1], [1], [1]] k = [[4, 2, 2, 1]] res = prod(k, prod(res, m0)) return res[0][0] % MOD