Show problems as
Classic problem #688MediumDynamic Programming

Knight Probability in Chessboard

Real-world version: The Piece That Stays on the Grid
Tracked in this browser only
Read Knight Probability in Chessboard on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstProbability & Expectations · Dynamic Programming, animated step by step

A piece stands on an n by n grid at row row and column column, both counted from zero.

The piece makes exactly k hops. One hop moves two squares along one direction together with one square along the perpendicular one, so eight hops are possible, and each of the eight is chosen with the same chance every time, whether or not it lands on the grid. Once the piece leaves the grid it stops there and never returns.

Return the chance that the piece is still on the grid once all k hops are done.

Examples

Example 1

Input
n = 3, k = 1, row = 0, column = 0
Output
0.25

From the corner of a three by three grid only two of the eight hops land back on it, so the chance is two eighths.

Example 2

Input
n = 3, k = 1, row = 1, column = 1
Output
0.0

From the middle of a three by three grid every one of the eight hops lands outside.

Example 3

Input
n = 8, k = 1, row = 3, column = 3
Output
1.0

The piece stands well inside an eight by eight grid, so every hop lands on it and the piece is certain to stay.

Constraints

  • 1 <= n <= 25
  • 0 <= k <= 100
  • 0 <= row <= n - 1
  • 0 <= column <= n - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def knight_probability(n: int, k: int, row: int, column: int) -> float:
Java
public double knightProbability(int n, int k, int row, int column)