Knight Dialer — LeetCode 935 Python Solution

MediumDynamic Programming
Problem
#935
Reading time
3 min

The problem

The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e.

Example

Input
n = 1
Output
10
Explanation
We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.

Python solution

Python
class Solution:
    def knightDialer(self, n: int) -> int:
        f = [1] * 10
        for _ in range(n - 1):
            g = [0] * 10
            g[0] = f[4] + f[6]
            g[1] = f[6] + f[8]
            g[2] = f[7] + f[9]
            g[3] = f[4] + f[8]
            g[4] = f[0] + f[3] + f[9]
            g[6] = f[0] + f[1] + f[7]
            g[7] = f[2] + f[6]
            g[8] = f[1] + f[3]
            g[9] = f[2] + f[4]
            f = g
        return sum(f) % (10**9 + 7)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the phone number
SpaceO(|\Sigma|), where \Sigma is the set of digits, and in this problem |\Sigma| = 10 auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 935. Knight Dialer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 935. Knight Dialer?
LeetCode 935. Knight Dialer is rated Medium on LeetCode.
What is the time complexity of LeetCode 935. Knight Dialer?
The Python solution on this page runs in O(n), where n is the length of the phone number.
What is the space complexity of LeetCode 935. Knight Dialer?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the set of digits, and in this problem |\Sigma| = 10 auxiliary space.
What topics does LeetCode 935. Knight Dialer cover?
LeetCode 935. Knight Dialer is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview