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
Knight Dialer: Phone Pad NavigationPhone Dialer1234567890Note: Digit 5 has NO valid knight moves!Knight's L-shaped moveMove ExamplesFrom 0: can go to 4, 6From 1: can go to 6, 8From 4: can go to 0, 3, 9From 5: nowhere! (isolated)From 6: can go to 0, 1, 7...DP avoids recalculation!Algorithm Steps1. Map valid moves for each digit2. Use DP: memo[digit][moves_left] = count3. Sum results from all starting positions
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.
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
67.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen