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 in Chessboard INPUT K 8 possible L-shaped moves n = 3 (board size) k = 2 (moves) row = 0 column = 0 ALGORITHM (DP) 1 Initialize DP Table dp[0][0][0] = 1.0 2 For each move k Iterate k from 1 to K 3 Update Probabilities dp[k][i][j] = sum/8 4 Sum Final Probs Sum all dp[K][i][j] Move Transitions (k=1): 1/8 1/8 From (0,0): 2 valid moves 6 off board P = 2/8 = 0.25 FINAL RESULT 1/32 1/32 After k=2 moves: Only 2 cells reachable Calculation: 1/32 + 1/32 = 2/32 = 1/16 = 0.0625 Output: 0.0625 Key Insight: Use 3D DP where dp[k][i][j] = probability of being at cell (i,j) after exactly k moves. Each move, probability divides by 8 (uniform random choice). Sum valid moves from 8 directions. Time: O(k * n^2), Space: O(n^2) with space optimization. TutorialsPoint - Knight Probability in Chessboard | Dynamic Programming Approach
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