MediumDynamic Programming

Knight Probability in Chessboard

LeetCode
1 approach, code in all languages

You are given an n x n chessboard and a knight that starts on cell (row, column). The knight must make exactly k moves. On every move it chooses one of the eight standard knight moves uniformly at random, so each candidate destination is picked with probability 1/8.

The knight keeps moving even if a chosen destination lands outside the board, but once it steps off the board it is lost and can never come back. Return the probability that the knight is still standing on the board after it has completed all k moves.

Example 1

Input: n = 3, k = 2, row = 0, column = 0

Output: 0.06250

From the corner (0,0) only two of the eight moves stay on the board. From each of those cells only two of the next eight moves stay on the board, so the surviving probability is 2 * (1/8) * (2/8) = 0.0625.

Example 2

Input: n = 1, k = 0, row = 0, column = 0

Output: 1.00000

With zero moves to make the knight never leaves its starting cell, so it remains on the board with certainty.

Constraints

  • 1 <= n <= 25
  • 0 <= k <= 100
  • 0 <= row, column <= n - 1
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now