All problems
1134MediumDynamic Programming

The Piece That Stays on the Grid

Tracked in this browser only
Write code

Trains the technique from

LeetCode 688Knight Probability in Chessboard

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a 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)
September 7
Apply