You are given an n x n chessboard and a knight. Initially, the knight is positioned at coordinates (row, column). You need to find the probability that the knight remains on the chessboard after making exactly k moves.
The knight moves in an L-shape: it can move two squares in one direction (horizontal or vertical) and then one square in the perpendicular direction. Given the initial position of the knight, determine the probability that after k moves, the knight will still be on the chessboard.
The movements can be in any of the following directions:
n, k, row, and column?
1 <= n <= 250 <= k <= 1000 <= row, column < ndp[i][j][m] defines the probability of the knight being at position (i, j) after m moves.dp[row][column][0] = 1 because the knight starts at the initial position with probability 1.1 to k, update the possible positions based on previous moves while ensuring the new positions are within the board.k moves, sum up the probabilities of all positions to get the result.def knightProbability(n: int, k: int, row: int, column: int) -> float:
# Directions a knight can move
directions = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
# DP table initialized with zeros
dp = [[[0 for _ in range(k + 1)] for _ in range(n)] for _ in range(n)]
# The initial position with 0 moves: probability is 1
dp[row][column][0] = 1
# Iterate over number of moves
for move in range(1, k + 1):
for r in range(n):
for c in range(n):
# If there's a probability to be at (r, c) with move-1
if dp[r][c][move - 1] > 0:
for dr, dc in directions:
new_r, new_c = r + dr, c + dc
# Check if the new position is within bounds
if 0 <= new_r < n and 0 <= new_c < n:
dp[new_r][new_c][move] += dp[r][c][move - 1] / 8.0
# Calculate the total probability of the knight being on the board after k moves.
result = 0
for r in range(n):
for c in range(n):
result += dp[r][c][k]
return result
# Example Usage
n = 3
k = 2
row = 0
column = 0
print(knightProbability(n, k, row, column)) # Output: The probability the knight is on the board after 2 moves
n is the size of the chessboard and k is the number of moves.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?