Leetcode 935: Knight Dialer

grid47
grid47
Exploring patterns and algorithms
Aug 5, 2024 8 min read

A knight is on a phone pad, and it can move to adjacent numeric cells according to its unique movement pattern (an L-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically). Given an integer n, you need to calculate how many distinct phone numbers of length n the knight can dial, starting from any numeric cell on the pad and performing n-1 valid knight jumps.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n, representing the length of the phone number to dial.
Example: Input: n = 3
Constraints:
• 1 <= n <= 5000
Output: Return the number of distinct phone numbers of length n that can be dialed by the knight, modulo 10^9 + 7.
Example: Output: 30
Constraints:
• The result should be returned modulo 10^9 + 7.
Goal: Calculate the number of valid knight paths of length n starting from each numeric cell on the phone pad. Use dynamic programming to compute the total count efficiently by caching intermediate results.
Steps:
• 1. Use dynamic programming to store the number of valid ways to reach each cell on the pad for each number of moves.
• 2. For each cell, recursively calculate the number of ways to reach it by performing valid knight moves.
• 3. Sum up the results for all starting cells, ensuring the answer is taken modulo 10^9 + 7.
Goal: The input size n can go up to 5000, so the solution needs to be optimized to handle large inputs efficiently.
Steps:
• 1 <= n <= 5000
• The result must be returned modulo 10^9 + 7.
Assumptions:
• The knight always starts on one of the numeric cells on the phone pad.
• Each jump must follow the valid knight's move pattern, as described.
Input: Input: n = 1
Explanation: For a phone number of length 1, any of the 10 numeric cells on the pad can be the starting point. Thus, there are 10 possible phone numbers.

Input: Input: n = 2
Explanation: For a phone number of length 2, we count all valid knight moves from each numeric cell. This gives a total of 20 possible valid phone numbers.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus