688. Knight Probability in Chessboard

1. Description

Given an N*N chessboard, a knight starts at the row and c column and makes k moves. 

Return the probability that the knight remains on the board.


2. Solution

Use dynamic programming.

For every step, calculate the number of ways to reach every gird.

After K steps, we can get the number of ways to reach (r,c).

The number divide pow(8,k) is the final answer.

这道题说明,走出格子有两种思路。

一个是从起点出发,走k步,统计有多少种方法可以走出格子。或者每个格子的和加起来就是留在格子上的方法。

一个是从每个点出发,走k步,统计有多少种方法可以走到出发点。

走出格子的方法+不走出格子的方法!= pow(4或者8,k)。


3. Code

    double knightProbability(int N, int K, int r, int c) {
        vector<vector<double> > p(N,vector<double>(N,1));
        for(int k=0;k<K;k++){
            vector<vector<double> > p2(N,vector<double>(N,0));
            for(int i=0;i<N;i++){
                for(int j=0;j<N;j++){
                    double cnt = 0;
                    for(int a=0;a<8;a++){
                        int x = i + xx[a];
                        int y = j + yy[a];
                        if(x>=0&&x<N&&y>=0&&y<N)
                            cnt+=p[x][y];
                    }
                    p2[i][j]=cnt;
                }
            }
            p=p2;
        }
        
        return double(p[r][c]*1.0/pow(8,K));
    }
   
    int xx[8]={-2,-2,-1,-1,1,1,2,2};
    int yy[8]={1,-1,2,-2,2,-2,1,-1};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值