Skip to content

Commit a8379d1

Browse files
committed
Add solution #688
1 parent 9b747a5 commit a8379d1

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,7 @@
519519
685|[Redundant Connection II](./0685-redundant-connection-ii.js)|Hard|
520520
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
521521
687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium|
522+
688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium|
522523
693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy|
523524
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
524525
696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy|
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 688. Knight Probability in Chessboard
3+
* https://leetcode.com/problems/knight-probability-in-chessboard/
4+
* Difficulty: Medium
5+
*
6+
* On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly
7+
* k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right
8+
* cell is (n - 1, n - 1).
9+
*
10+
* A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells
11+
* in a cardinal direction, then one cell in an orthogonal direction.
12+
*
13+
* Each time the knight is to move, it chooses one of eight possible moves uniformly at random
14+
* (even if the piece would go off the chessboard) and moves there.
15+
*
16+
* The knight continues moving until it has made exactly k moves or has moved off the chessboard.
17+
*
18+
* Return the probability that the knight remains on the board after it has stopped moving.
19+
*/
20+
21+
/**
22+
* @param {number} n
23+
* @param {number} k
24+
* @param {number} row
25+
* @param {number} column
26+
* @return {number}
27+
*/
28+
var knightProbability = function(n, k, row, column) {
29+
const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]];
30+
const dp = new Map();
31+
32+
return calc(k, row, column);
33+
34+
function calc(movesLeft, r, c) {
35+
if (r < 0 || r >= n || c < 0 || c >= n) return 0;
36+
if (movesLeft === 0) return 1;
37+
38+
const key = `${movesLeft},${r},${c}`;
39+
if (dp.has(key)) return dp.get(key);
40+
41+
let prob = 0;
42+
for (const [dr, dc] of moves) {
43+
prob += calc(movesLeft - 1, r + dr, c + dc) / 8;
44+
}
45+
46+
dp.set(key, prob);
47+
return prob;
48+
}
49+
};

0 commit comments

Comments
 (0)