Knight Probability in Chessboard - Problem

On an n × n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n-1, n-1).

A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

The knight continues moving until it has made exactly k moves or has moved off the chessboard.

Return the probability that the knight remains on the board after it has stopped moving.

Input & Output

Example 1 — Small Board
$ Input: n = 3, k = 2, row = 0, column = 0
Output: 0.0625
💡 Note: Knight starts at (0,0). After 1 move, it can reach (1,2) and (2,1). After 2nd move, some paths stay on board, some don't. Total probability is 1/16 = 0.0625
Example 2 — No Moves
$ Input: n = 1, k = 0, row = 0, column = 0
Output: 1.0
💡 Note: No moves means knight stays at starting position, so probability of staying on board is 1.0
Example 3 — Center Position
$ Input: n = 8, k = 1, row = 4, column = 4
Output: 1.0
💡 Note: Knight at center of 8x8 board. All 8 possible moves stay on board, so probability is 8/8 = 1.0

Constraints

  • 1 ≤ n ≤ 25
  • 0 ≤ k ≤ 100
  • 0 ≤ row, column < n

Visualization

Tap to expand
Knight Probability Problem Overviewn×n ChessboardKnight has 8 possible moves:• Each move chosen randomly• Some moves go off the board• Calculate probability of staying onAfter k moves:Probability = (Valid positions) / (All paths)Range: [0.0, 1.0]🎯 Key Insight: Use DP to track probability at each position after each move
Understanding the Visualization
1
Input
n×n chessboard, knight at (row, col), k moves to make
2
Process
Knight randomly picks 1 of 8 possible moves each turn
3
Output
Probability knight remains on board after exactly k moves
Key Takeaway
🎯 Key Insight: Track the probability of being at each board position after each move using dynamic programming
Asked in
Google 25 Facebook 18 Amazon 12
89.6K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen