688. Knight Probability in Chessboard

Problem:

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.

思路

Solution (C++):

double knightProbability(int N, int K, int r, int c) {
    vector<vector<vector<double>>> dp(K+1, vector<vector<double>>(N, vector<double>(N, -1.0)));
    return helper(dp, N, K, r, c) / pow(8, K);
}
double helper(vector<vector<vector<double>>>& dp, int N, int k, int r, int c) {
    if (r < 0 || r > N-1 || c < 0 || c > N-1)  return 0.0;
    if (k == 0)  return 1.0;
    if (dp[k][r][c] != -1.0)  return dp[k][r][c];
    dp[k][r][c] = 0.0;
    for (int i = -2; i <= 2; ++i) {
        if (i == 0)  continue;
        dp[k][r][c] += helper(dp, N, k-1, r+i, c-(3-abs(i))) + helper(dp, N, k-1, r+i, c+(3-abs(i)));
    }
    return dp[k][r][c];
}

性能

Runtime: 8 ms  Memory Usage: 8.5 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

原文链接: https://www.cnblogs.com/dysjtu1995/p/12726875.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    688. Knight Probability in Chessboard

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342948

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午1:50
下一篇 2023年3月2日 上午1:50

相关推荐