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