zoukankan      html  css  js  c++  java
  • 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

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Hadoop 解除 “Name node is in safe mode”
    ubuntu永久修改主机名
    ssh免密码登录
    su 和 su- 会影响环境变量
    卸载ubuntu自带openJDK,更改成自己的JDK版本
    ubuntu安装jdk 1.6
    147.Insertion Sort List
    145.Binary Tree Postorder Traversal
    144.Binary Tree Preorder Traversal
    143.Reorder List
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12726875.html
Copyright © 2011-2022 走看看