935. Knight Dialer
https://leetcode.com/problems/knight-dialer/
Last updated
Was this helpful?
https://leetcode.com/problems/knight-dialer/
Last updated
Was this helpful?
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:
Example 2:
Example 3:
Note:
1
<
= N
<
= 5000
初始时可以在手机键盘任意按键上,问按象棋马的走法,跳N-1步后所有可能的跳法的数目。一共N-1步,每步action为从上一步所在按键蹦到另一个可蹦的按键,受限于两个按键是否符合跳马,因此状态中encode哪步落在了哪个按键,dp[i][j]存第i步落在j的总共的可能数。
还有O(lgN)解法,利用了马尔科夫链。
时间复杂度O(N).