Link: https://leetcode.com/problems/knight-dialer
Solution:
DSA: DP
Intuition
This is kind of a graph problem. Just do DFS with a cache for all possibilities and return 1 as the base case when length == n.
There is also a crazy math solution that I don’t really understand. Maybe memorize it if possible.
Implementation
This is the diagram from LC editorial:
Visual
Memory encoding
Review 1
As an experiment I wanted to see if this problem is possible with backtracking. Indeed it is but it results in TLE. Furthermore, when you take the current move out of the function, you can no longer cache it. A cacheable function must be a 2d DP dfs(move, length)
because for example the move 3
at a length of 5
will have the same number of possibilities no matter what, so it make sense to process this only once and simply return the cached value upon future visitations (in this case visitations to (3, 5)
).