KatInterview

Counting Knight-Walk Phone Numbers on a Keypad

Dynamic ProgrammingAuto-graded · 19 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggraphmodular-arithmetic

Last updated

Count length-n digit strings formed by knight jumps on a phone keypad, modulo 1e9+7, using DP over a small fixed graph.

Knight Walk Phone Numbers

Imagine a telephone keypad laid out like this:

1  2  3
4  5  6
7  8  9
*  0  #

A chess knight stands on one of the keys. It may only occupy the ten digit keys 0 through 9; the keys * and # are off limits. Each jump is a standard knight move: two cells in one direction (horizontal or vertical) and then one cell perpendicular to it.

Each time the knight lands on a key, you write down that digit. Starting on any digit key of your choice and making legal jumps, the digits you record form a number string. Your task is to count how many different digit strings of length exactly n can be produced this way.

Since the count can be huge, return it modulo 1000000007.

Details

  • The first digit of the string is the key where the knight starts, so a string of length n involves exactly n - 1 jumps.
  • Every one of the ten digits is a valid starting key, including 5. Note that 5 has no legal jumps, so it can only appear in a string when n = 1.
  • Two strings are different if they differ at any position.

Function

Implement count_knight_numbers(n), which returns the number of valid length-n digit strings modulo 1000000007.

Constraints

  • 1 <= n <= 5000
  • The result must be returned modulo 1000000007.

Examples

Example 1

Input: count_knight_numbers(1)

Output: 10

Example 2

Input: count_knight_numbers(2)

Output: 20

Example 3

Input: count_knight_numbers(3)

Output: 46

Hints

Hint 1

Think of the digits as nodes in a graph, with an edge wherever a knight can jump between two keys. A string of length n is a walk with n - 1 jumps.

Hint 2

Let ways[d] be the number of valid strings of the current length that end at digit d. Start with ways[d] = 1 for every digit, then build the next length from the previous one.

Hint 3

To extend by one digit, add ways[d] to each digit reachable from d. Reduce modulo 1000000007 at every addition, run the update n - 1 times, and sum the final ten values.