LeetCode 935: Knight Dialer Solution

Master LeetCode problem 935 (Knight Dialer), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

935. Knight Dialer

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can maintain a 2D array to store the number of ways to reach each number from the previous number for each hop. We iterate through each hop and update the counts based on the possible knight moves. Finally, we sum up the counts for all numbers in the last row (representing the total number of ways to dial a number of length n).

Algorithm:

  1. Initialize a 2D array dp of size 10xn to store the counts of ways to reach each number for each hop.
  2. Initialize the first row of dp to 1, as there is only one way to dial a number of length 1 from any starting number.
  3. Iterate through each hop from 1 to n.
  4. For each hop, calculate the counts by considering the possible knight moves for each number.
  5. Update the counts in dp based on the previous hop's counts.
  6. Finally, sum up the counts for all numbers in the last row of dp to get the total number of ways to dial a number of length n.

Time Complexity: O(n)
Space Complexity: O(n)

:

Solution Code

class Solution {
    public int knightDialer(int n) {
        int MOD = 1000000007;
        int[][] moves = {
            {4, 6}, {6, 8}, {7, 9}, {4, 8}, {3, 9, 0},
            {}, {1, 7, 0}, {2, 6}, {1, 3}, {2, 4}
        };
        
        int[][] dp = new int[10][n];
        for (int i = 0; i < 10; i++) {
            dp[i][0] = 1;
        }
        
        for (int hop = 1; hop < n; hop++) {
            for (int num = 0; num < 10; num++) {
                for (int nextNum : moves[num]) {
                    dp[nextNum][hop] = (dp[nextNum][hop] + dp[num][hop - 1]) % MOD;
                }
            }
        }
        
        int totalWays = 0;
        for (int i = 0; i < 10; i++) {
            totalWays = (totalWays + dp[i][n - 1]) % MOD;
        }
        
        return totalWays;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 935 (Knight Dialer)?

This page provides optimized solutions for LeetCode problem 935 (Knight Dialer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 935 (Knight Dialer)?

The time complexity for LeetCode 935 (Knight Dialer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 935 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 935 in Java, C++, or Python.

Back to LeetCode Solutions