- Knight Probability in Chessboard
这是最近的fb高频题,在一亩三分地上看到有人post原题
典型的dp算法
dp[i][j]表示在(i,j)位置上,棋子走完一步还在棋盘上的可能总和。
初始为0,表示没走的时候棋子都在棋盘上。
当走一步,(K=0)时,dp[i][j]就会update
当再走一步,(K=1)时,dp[i][j]又会update。
这个code,是每走一步,算出所有(i,j)position还在棋盘上的可能性。
最后pick出(r,c)上的值就好了。
如果(i,j)不容易理解,可以试着举个例子:
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.
3*3的棋盘,
初始位置在(0,0),
走一步,只有两种可能还在棋盘上,
这两种可能位置是(1,2),(2,1)。
在位置(1,2)上,走一步,有两种可能还在棋盘上。
在位置(2,1)上,走一步,有两种可能还在棋盘上。
(上面的这一部分就是在loop K=0里都算好了)
然后loop K=1(走第二步)的时候,(0,0)position还在棋盘上的可能性就是4.
最终有4种可能还在棋盘上,但是对于K=2,所有的可能是8^2 = 64
所以结果是:4/64 = 0.0625
class Solution {
public:
double knightProbability(int N, int K, int r, int c) {
vector<vector<double>>dp(N,vector<double>(N,1));
vector<pair<int,int>>moves{{-2,1}, {-2,-1}, {-1,2}, {-1,-2}, {1, 2}, {1,-2}, {2, 1}, {2, -1}};
for(int mc = 0; mc < K; mc++)
{
vector<vector<double>>t(N, vector<double>(N, 0));
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
for(auto move : moves)
{
int ni = i + move.first;
int nj = j + move.second;
if(ni < 0 || ni >= N || nj < 0 || nj >= N)
{
continue;
}
t[i][j] += dp[ni][nj];
}
}
}
dp = t;
}
return dp[r][c]/pow(8, K);
}
};