[Swift Weekly Contest 109]LeetCode935. 騎士撥號器 | 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 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
.
Example 1:
Input: 1
Output: 10
Example 2:
Input: 2
Output: 20
Example 3:
Input: 3
Output: 46
Note:
1 <= N <= 5000
國際象棋中的騎士可以按下圖所示進行移動:
.
這一次,我們將 “騎士” 放在電話撥號盤的任意數字鍵(如上圖所示)上,接下來,騎士將會跳 N-1 步。每一步必須是從一個數字鍵跳到另一個數字鍵。
每當它落在一個鍵上(包括騎士的初始位置),都會撥出鍵所對應的數字,總共按下 N
位數字。
你能用這種方式撥出多少個不同的號碼?
因為答案可能很大,所以輸出答案模 10^9 + 7
。
示例 1:
輸入:1 輸出:10
示例 2:
輸入:2 輸出:20
示例 3:
輸入:3 輸出:46
提示:
1 <= N <= 5000
284ms
1 class Solution { 2 func knightDialer(_ N: Int) -> Int { 3 var N = N 4 var mod:Int64 = 1000000007 5 N -= 1 6 var dp:[Int64] = [Int64](repeating: 1,count: 10) 7 for i in 0..<N 8 { 9 var ndp:[Int64] = [Int64](repeating: 0,count: 10) 10 ndp[0] = dp[4] + dp[6] 11 ndp[1] = dp[6] + dp[8] 12 ndp[2] = dp[7] + dp[9] 13 ndp[3] = dp[4] + dp[8] 14 ndp[4] = dp[3] + dp[9] + dp[0] 15 ndp[6] = dp[1] + dp[7] + dp[0] 16 ndp[8] = dp[1] + dp[3] 17 ndp[7] = dp[2] + dp[6] 18 ndp[9] = dp[2] + dp[4] 19 for j in 0..<10 20 { 21 ndp[j] %= mod 22 } 23 dp = ndp 24 } 25 var ret:Int64 = 0 26 for i in 0..<10 27 { 28 ret += dp[i] 29 } 30 return Int(ret % mod) 31 } 32 }