Skip to content

Commit eedf0f1

Browse files
committed
Add solution #935
1 parent efad2c0 commit eedf0f1

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,7 @@
744744
932|[Beautiful Array](./solutions/0932-beautiful-array.js)|Medium|
745745
933|[Number of Recent Calls](./solutions/0933-number-of-recent-calls.js)|Easy|
746746
934|[Shortest Bridge](./solutions/0934-shortest-bridge.js)|Medium|
747+
935|[Knight Dialer](./solutions/0935-knight-dialer.js)|Medium|
747748
937|[Reorder Data in Log Files](./solutions/0937-reorder-data-in-log-files.js)|Medium|
748749
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
749750
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|

Diff for: solutions/0935-knight-dialer.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)