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.
The knight always initially starts on the board.
那么分母最好算,每步走有8种跳法,那么K步就是8的K次方种了。关键是要求出分子。还是要用DP来做,我们可以用三维DP数组,也可以用二维DP数组来做,这里为了省空间,我们就用二维DP数组来做,其中dp[i][j]表示在棋盘(i, j)位置上走完当前步骤还留在棋盘上的走法总和,初始化为1,我们其实将步骤这个维度当成了时间维度在不停更新。好,下面我们先写出8种‘日’字走法的位置的坐标,就像之前遍历迷宫上下左右四个方向坐标一样,这不过这次位置变了而已。然后我们一步一步来遍历,每一步都需要完整遍历一遍棋盘的每个位置,新建一个临时数组t,大小和dp数组相同,但是初始化为0,然后对于遍历到的棋盘上的每一个格子,我们都遍历8中解法,如果新的位置不在棋盘上了,直接跳过,否则就加上上一步中的dp数组中对应的值,遍历完棋盘后,将dp数组更新为这个临时数组t,
建议和leetcode 576. Out of Boundary Paths 很棒的DP动态规划做法 一起学习
这道题需要注意跌是使用double去做遍历,否者会error
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
double knightProbability(int N, int K, int r, int c)
{
if (K == 0)
return 1;
vector<vector<int>> dir{ {-2,1},{ 2, 1},{ -2,-1 },{ 2, -1 },{-1,2},{ 1,2 },{ -1,-2 },{ 1,-2 } };
vector<vector<double>> dp(N, vector<double>(N, 1));
for (int k = 0; k < K; k++)
{
vector<vector<double>> tmp(N, vector<double>(N, 0));
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (vector<int> d : dir)
{
int x = i + d[0], y = j + d[1];
if(x>=0 && x<N && y>=0 && y<N)
tmp[i][j] += dp[x][y];
}
}
}
dp = tmp;
}
double res = dp[r][c] / pow(8, K);
return res;
}
};