MediumDynamic Programming

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

The Piece That Stays on the Grid is our own problem on the technique behind Knight Probability in Chessboard: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free