Leetcode 688. Knight Probability in Chessboard
The problem is to determine the probability that a knight stays on an N x N
chessboard after making exactly K
moves, starting from position (r, c)
.
A knight in chess has eight possible moves. If the knight moves off the board, it is no longer considered. We have to find the probability that the knight stays on the board after K
moves.
double knightProbability(int N, int K, int r, int c);
N
is the dimension of the chessboard.K
is the number of moves the knight will make.r
and c
are the starting row and column of the knight.knightProbability(3, 2, 0, 0); // returns 0.0625
knightProbability(3, 1, 0, 0); // returns 0.25
N
, K
, r
, and c
are always within reasonable bounds such that no invalid accesses occur.1 <= N <= 25
, and 0 <= r, c < N
.dp
where dp[k][i][j]
represents the probability of being on cell (i, j)
after k
moves.dp[0][r][c] = 1.0
as the starting position.0
to K-1
, update the probabilities based on the knight’s possible moves.K
moves, sum up the probabilities that the knight is still on the board to get the final result.#include <vector>
using namespace std;
class Solution {
public:
double knightProbability(int N, int K, int r, int c) {
// Direction vectors for knight moves
vector<vector<int>> directions = \{\{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
// DP table
vector<vector<vector<double>>> dp(K + 1, vector<vector<double>>(N, vector<double>(N, 0.0)));
// Initial position
dp[0][r][c] = 1.0;
// Fill DP table
for (int k = 1; k <= K; ++k) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (dp[k - 1][i][j] > 0) {
for (const auto& direction : directions) {
int ni = i + direction[0];
int nj = j + direction[1];
if (ni >= 0 && ni < N && nj >= 0 && nj < N) {
dp[k][ni][nj] += dp[k - 1][i][j] / 8.0;
}
}
}
}
}
}
// Calculate the total probability the knight is still on the board after K moves
double probability = 0.0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
probability += dp[K][i][j];
}
}
return probability;
}
};
K
moves, we update each cell (i, j)
based on constant number (8) of possible previous positions.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?