Knight Dialer - Problem
Imagine you have a chess knight placed on a phone dialer pad! A knight moves in an L-shape: either 2 squares vertically and 1 horizontally, or 2 squares horizontally and 1 vertically.
The phone pad looks like this:
1 2 3 4 5 6 7 8 9 0
Given an integer n, determine how many distinct phone numbers of length n you can dial by moving the knight around the pad. You can start on any numeric key (0-9), then make exactly n-1 valid knight moves.
Goal: Count all possible phone numbers of length n that can be formed by valid knight moves.
Note: Since the answer can be very large, return it modulo 10^9 + 7.
Input & Output
example_1.py โ Small Case
$
Input:
n = 1
โบ
Output:
10
๐ก Note:
With only 1 digit, we can start on any of the 10 digits (0-9) and don't need to make any moves. So there are 10 possible phone numbers of length 1.
example_2.py โ Two Digits
$
Input:
n = 2
โบ
Output:
20
๐ก Note:
For length 2, we need exactly 1 knight move. From digit 5, no moves are possible. From other digits, we can make various moves: 0โ4,6; 1โ6,8; 2โ7,9; etc. Total valid 2-digit numbers: 20.
example_3.py โ Larger Case
$
Input:
n = 3131
โบ
Output:
136006598
๐ก Note:
For very large n, the number of possible phone numbers grows exponentially, but due to the modulo operation (10^9 + 7), we return 136006598.
Constraints
- 1 โค n โค 5000
- Answer should be returned modulo 109 + 7
- Knight can start on any digit (0-9)
- All moves must be valid knight moves within the phone pad
Visualization
Tap to expand
Understanding the Visualization
1
Map the Moves
First, identify all valid knight moves from each digit on the phone pad
2
Build the Cache
Use dynamic programming to store results for each (digit, moves_left) combination
3
Count Paths
Sum up all possible paths from each starting digit to get the final answer
Key Takeaway
๐ฏ Key Insight: Instead of exploring every possible path (exponential), we count the number of ways to reach each digit after exactly k moves, building up the solution incrementally using dynamic programming.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code