|
| 1 | +/** |
| 2 | + * 935. Knight Dialer |
| 3 | + * https://leetcode.com/problems/knight-dialer/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * The chess knight has a unique movement, it may move two squares vertically and one square |
| 7 | + * horizontally, or two squares horizontally and one square vertically (with both forming |
| 8 | + * the shape of an L). The possible movements of chess knight are shown in this diagram: |
| 9 | + * |
| 10 | + * A chess knight can move as indicated in the chess diagram below. |
| 11 | + * |
| 12 | + * We have a chess knight and a phone pad as shown below, the knight can only stand on a |
| 13 | + * numeric cell (i.e. blue cell). |
| 14 | + * |
| 15 | + * Given an integer n, return how many distinct phone numbers of length n we can dial. |
| 16 | + * |
| 17 | + * You are allowed to place the knight on any numeric cell initially and then you should |
| 18 | + * perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps. |
| 19 | + * |
| 20 | + * As the answer may be very large, return the answer modulo 109 + 7. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number} n |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var knightDialer = function(n) { |
| 28 | + const MOD = 1e9 + 7; |
| 29 | + const moves = [ |
| 30 | + [4, 6], [6, 8], [7, 9], [4, 8], |
| 31 | + [0, 3, 9], [], [0, 1, 7], [2, 6], |
| 32 | + [1, 3], [2, 4] |
| 33 | + ]; |
| 34 | + let prevCounts = new Array(10).fill(1); |
| 35 | + |
| 36 | + for (let jump = 1; jump < n; jump++) { |
| 37 | + const currCounts = new Array(10).fill(0); |
| 38 | + for (let digit = 0; digit < 10; digit++) { |
| 39 | + for (const nextDigit of moves[digit]) { |
| 40 | + currCounts[nextDigit] = (currCounts[nextDigit] + prevCounts[digit]) % MOD; |
| 41 | + } |
| 42 | + } |
| 43 | + prevCounts = currCounts; |
| 44 | + } |
| 45 | + |
| 46 | + return prevCounts.reduce((sum, count) => (sum + count) % MOD, 0); |
| 47 | +}; |
0 commit comments