Knight Probability in Chessboard:棋盘上计算K步之后棋子仍在棋盘上的概率
来源:互联网 发布:visual c 数据库开发 编辑:程序博客网 时间:2024/05/24 06:43
On an N
xN
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, 0Output: 0.0625Explanation: 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.思路:动态规划
f[r][c][steps]=∑dr,dcf[r+dr][c+dc][steps−1]/8.0
每次只计算当前一步和下一步,所以用二维数组即可。计算棋盘上所有点在本轮可能被访问的概率。最后棋盘上所有点求和就是仍在棋盘上的概率。
时间复杂度O(KN^2) 因为if所在的循环是常数级。
空间复杂度O(N^2)
class Solution { public double knightProbability(int N, int K, int r, int c) { double[][] d = new double[N][N]; int[] R = {2,2,-2,-2,1,1,-1,-1}; int[] C = {1,-1,1,-1,2,-2,2,-2}; d[r][c] = 1; for(int round = 0;round < K;round++){ double[][] dtemp = new double[N][N]; for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ for(int a = 0 ;a < 8; a++){ int rr = i + R[a]; int cc = j + C[a]; if(rr >= 0 && rr < N & cc >= 0 && cc < N){ dtemp[rr][cc] += d[i][j]/8; } } } } d = dtemp; } double result = 0; for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ result += d[i][j]; } } return result; }}
- Knight Probability in Chessboard:棋盘上计算K步之后棋子仍在棋盘上的概率
- Knight Probability in Chessboard
- uva 10237 n x n棋盘上放k个棋子 棋子不能在同一斜线上 求总类数
- poj1657-Distance on Chessboard(棋盘上的距离)-C语言-简单计算
- 688. Knight Probability in Chessboard
- 688. Knight Probability in Chessboard
- 688. Knight Probability in Chessboard
- 688. Knight Probability in Chessboard
- 棋盘上放棋子(任意两个棋子不相邻)
- 棋盘上的距离
- 棋盘上的麦子
- 棋盘上的距离
- 棋盘上的距离
- 棋盘上的距离
- 棋盘上的守卫
- 棋盘上的距离
- LWC 52:688. Knight Probability in Chessboard
- Knight Probability in Chessboard问题及解法
- List集合排序
- C#数组总结
- java多线程之Lock类的使用
- Oracle如何修改字段数据类型(转)
- Androd用WebView播放gif动画
- Knight Probability in Chessboard:棋盘上计算K步之后棋子仍在棋盘上的概率
- 第4大周的反思
- C++ 隐式转换
- 快速排序
- 条件表达式a?b:c是什么意思
- Ealsticsearch 5.x IK分词器
- jquery 需要加载页面触发一个js方法
- Android 动画的实现
- lvs+keepalived和haproxy+heartbeat区别