688. Knight Probability in Chessboard
On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).
A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.
Example:
Input: 3, 2, 0, 0
Output: 0.0625
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
Note:
- N will be between 1 and 25.
- K will be between 0 and 100.
- 3.The knight always initially starts on the board.
方法1: dynamic programming
花花:https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/
思路:
首先设置好一个dirs array(这里用array会比vector要快很多),存储着knight每次可以走的八个方位。我们做k次循环,每一次都单独开辟一个n*n的新棋盘来替代旧的,每一个格子用来标示在第k步有多少种走法能够落在(i, j)这个格子。那么对于每个格子来说,它只需要从上一轮的八个相对位置累计来获得本轮的probability。换句话说,对于本轮的每个非零位置(i, j),我们将dp[i][j转移到它能够走到的下一步位置。在统计完一轮后,新的棋盘tmp代替dp,继续下一轮。最后遍历一次累计总probability,骑士在k步内的全部走法是pow(8,k)。
Complexity
Time complexity: O(kN^2)
Space complexity: O(N^2)
class Solution {
public:
double knightProbability(int N, int K, int r, int c) {
int dirs[8][2] = {{1, 2}, {-1, -2}, {1, -2}, {-1, 2},
{2, 1}, {-2, -1}, {2, -1}, {-2, 1}};
vector<vector<double>> dp(N, vector<double>(N, 0.0));
dp[r][c] = 1;
for (int k = 0; k < K; k++) {
vector<vector<double>> tmp(N, vector<double>(N, 0.0));
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (dp[i][j]) {
for (auto dir: dirs) {
int x = i + dir[0];
int y = j + dir[1];
if (x < 0 || x >= N || y < 0 || y >= N) continue;
tmp[x][y] += dp[i][j];
}
}
}
}
swap(dp, tmp);
}
double result = 0.0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result += dp[i][j];
}
}
return result / pow(8, K);
}
};