[leetcode]688. Knight Probability in Chessboard

162 篇文章 0 订阅
23 篇文章 0 订阅

[leetcode]688. Knight Probability in Chessboard


Analysis

富婆怎么还不来找我—— [每天刷题并不难0.0]

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.
在这里插入图片描述

Explanation:

每走一步,该棋子没有越界的概率等于之前八个可能方向上棋子没有越界的概率加和。

Implement

class Solution {
public:
    double knightProbability(int N, int K, int r, int c) {
        vector<vector<vector<double>>> dp(K+1, vector<vector<double>>(N, vector<double>(N, 0.0)));
        dp[0][r][c] = 1;
        for(int k=0; k<K; k++){
            for(int i=0; i<N; i++){
                for(int j=0; j<N; j++){
                    for(auto d:dir){
                        int cur_r = i+d[0];
                        int cur_c = j+d[1];
                        if(isRemain(cur_r, cur_c, N))
                            dp[k+1][cur_r][cur_c] += (dp[k][i][j]/8);
                    }
                }
            }
        }
        double res = 0;
        for(int i=0; i<N; i++){
            for(int j=0; j<N; j++)
                res += dp[K][i][j];
        }
        return res;
    }
    bool isRemain(int r, int c, int N){
        if(r>=0 && c>=0 && r<N && c<N)
            return true;
        return false;
    }
private:
    int dir[8][8] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, -1}, {-2, 1}};
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值