【leetcode】688.Knight Probability in Chessboard(“马”在棋盘上的概率)
688. Knight Probability in Chessboard
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.
已知一个 NxN 的国际象棋棋盘,棋盘的行号和列号都是从 0 开始。即最左上角的格子记为 (0, 0),最右下角的记为 (N-1, N-1)。
现有一个 “马”(也译作 “骑士”)位于 (r, c) ,并打算进行 K 次移动。
如下图所示,国际象棋的 “马” 每一步先沿水平或垂直方向移动 2 个格子,然后向与之相垂直的方向再移动 1 个格子,共有 8 个可选的位置。
现在 “马” 每一步都从可选的位置(包括棋盘外部的)中独立随机地选择一个进行移动,直到移动了 K 次或跳到了棋盘外面。
求移动结束后,“马” 仍留在棋盘上的概率。
示例:
输入: 3, 2, 0, 0
输出: 0.0625
解释:
输入的数据依次为 N, K, r, c
第 1 步时,有且只有 2 种走法令 “马” 可以留在棋盘上(跳到(1,2)或(2,1))。对于以上的两种情况,各自在第2步均有且只有2种走法令 “马” 仍然留在棋盘上。
所以 “马” 在结束后仍在棋盘上的概率为 0.0625。
注意:
N 的取值范围为 [1, 25]
K 的取值范围为 [0, 100]
开始时,“马” 总是位于棋盘上
思路:
- I. 暴力遍历
1. 简单暴力遍历 K 次移动,马到达的每个位置。
2. 然后统计棋盘中的位置数量,棋盘外的数量。
- 已知 (棋盘内数量) + (棋盘外数量) =
8^K
- 所以只需要记录(棋盘内数量),即可知道概率 = (棋盘内数量)/(
8^K
) - 但是遍历如果采用深搜,遍历层数太多(100层)
- 如果采用广搜,会造成指数爆炸(
8^100
) - 考虑到棋盘最大为
25*25
,那么广搜最大节点也只是25*25 = 625
。 - 另一个问题,如果统计出现的次数,数据会溢出(
8^100
,平摊到棋盘每个位置怎么算都会溢出) - 采用瓜分概率的方式:
第 1 步有 1 个位置,每个位置概率为 1
第 2 步有 8 个位置,每个位置概率为 1/8
第 3 步有 64 个位置,每个位置概率为 1/8/8
...
- 总结以上描述,方法为:
1. 广搜(位置映射到棋盘,最大为 25*25)
2. 搜索的下一个位置保存原位置 1/8 的概率。
3. 搜索结束,统计所有位置的概率总和即为结果。
CODE:
class Solution {
public:
double knightProbability(int N, int K, int r, int c) {
int rr[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int cc[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
int curIdx = 0;
int nexIdx = 1;
double m[2][25][25] = { 0 };
m[curIdx][r][c] = 1;
while(K--) {
for (int ri=0; ri<N; ++ri) {
for (int ci=0; ci<N; ++ci) {
double val = m[curIdx][ri][ci];
if (!val) continue;
for (int i=0; i<8; ++i) {
int r = rr[i] + ri;
int c = cc[i] + ci;
if (r >= 0 && r < N && c >= 0 && c < N) {
m[nexIdx][r][c] += val / 8;
}
}
}
}
nexIdx = curIdx;
curIdx = 1 - curIdx;
memset(&m[nexIdx][0][0], 0, sizeof(double) * N * (25));
}
double ret = 0;
for (int ri=0; ri<N; ++ri) {
for (int ci=0; ci<N; ++ci) {
ret += m[curIdx][ri][ci];
}
}
return ret;
}
};