Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

935. Knight Dialer

Dynamic Programming

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)

:

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.