Problem 688 · LeetCode 688(opens in a new tab)
Knight Probability in Chessboard
MediumDynamic programming
A knight stands on square (row, column) of an n × n chessboard, with rows and columns numbered from 0. It is going to try to make k moves.
Each move, the knight picks one of its 8 L-shaped jumps uniformly at random, even jumps that would carry it off the board. Once it leaves the board it stops for good; otherwise it keeps going until it has made k moves.
Return the probability that the knight is still on the board at the end.
Example 1
Input: n = 4, k = 2, row = 0, column = 3 Output: 0.125 Why: 2 of 8 first jumps stay on; from each, 4 of 8 do
2 more examples and the constraints
Example 2
Input: n = 3, k = 1, row = 1, column = 1 Output: 0.0 Why: every jump from the centre of a 3 × 3 board leaves it
Example 3
Input: n = 5, k = 0, row = 2, column = 3 Output: 1.0 Why: no moves, so the knight is surely still on
Constraints
- The board side n is between 1 and 25
- The move count k is between 0 and 100
- The start square is on the board
- Answers within 10⁻⁵ of the true value are accepted
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with memoO(k·n²)
- Two probability boardsO(k·n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 25 and k = 100 | Verdict |
|---|---|---|---|
| Recursion with memo | O(k·n²) | Passes; large memo and deep calls | |
| Two probability boards | O(k·n²) | Best; two boards, no recursion |
n = side of the board, k = number of moves.
Edge cases to test
- No moves. k = 0 gives exactly 1, wherever the knight starts.
- Tiny board. On a 1 × 1 or 2 × 2 board every jump leaves, so any k ≥ 1 gives 0.
- Centre of 3 × 3. All 8 jumps leave the board at once: 0.
- Many moves. k = 100 on a 25 × 25 board: chances get very small but stay well within a double's range.
Common mistakes
- Dividing only by the number of on-board jumps; the knight picks among all 8, and off-board picks end the walk.
- Updating the same board in place, so shares sent this move get spread again in the same move.
- Plain recursion without a memo, which makes 8ᵏ calls.
How to talk through it
- 1Clarify. Does the knight choose among all 8 jumps even near the edge? Does leaving the board end the walk? How precise must the answer be?
- 2State the recurrence. stay(m, r, c) is the average of stay(m − 1) over the 8 jumps; 0 off the board, 1 when m = 0.
- 3Add the memo. Only (k + 1) · n² distinct states, so cache them: O(k·n²).
- 4Turn it forward. Spread probability from the start square one move at a time with two boards, then sum the last board.
- 5Test out loud. Run k = 0, a 1 × 1 board, the centre of a 3 × 3 board, and the corner of a 4 × 4 board.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?