Question:
思路
这个题我们要计算k moves之后, knight 还留在board上的概率. 那说白了, 就是我们要计算knight去每个cell 上的概率after k moves 之后.
那我们的knight, 每一个move, 我们的knight可以都可以走8个方向, 那说白了就是, 如果我的knight 初始位置就是当前位置. 那knight 在 0 moves 的时候, 它的初始位置的概率就是1, 然后那8歌方向的位置分别可以分给1/8的概率, 这就是after 1 move. 那after 2 move 呢?就是1move的那8个position 再分别给他们的8个方向分它的1/8概率… 就这么循环往复. k 次.
答案给的是brute force, 然后dp. 存两个 dp table,一个是用来存前一轮move的所有位置的概率. 另一个存的是当前这一轮move, 所有位置的概率. 因为算当前概率就是需要前一轮的嘛… 所以, 题目答案给的就是, 最外层循环k次, 然后里面每一轮棋盘所有位置上的概率都算一遍…
最后k循环结束之后, 再把mem table上所有概率加一起, 就是knight 留在棋盘上的概率.
class Solution {
public double knightProbability(int N, int K, int sr, int sc) {
// mem table of previous steps
double[][] dp = new double[N][N];
// 8 position that a knight can go
int[] dr = new int[]{2, 2, 1, 1, -1, -1, -2, -2};
int[] dc = new int[]{1, -1, 2, -2, 2, -2, 1, -1};
dp[sr][sc] = 1;
for (; K > 0; K--) {
// mem table of current steps
double[][] dp2 = new double[N][N];
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
// find all 8 possible positions that current position can go
for (int k = 0; k < 8; k++) {
int cr = r + dr[k];
int cc = c + dc[k];
if (0 <= cr && cr < N && 0 <= cc && cc < N) {
// if one direction is possible, we distribute probility
dp2[cr][cc] += dp[r][c] / 8.0;
}
}
}
}
dp = dp2;
}
// after iterating k loops, we finally get probability of every position in the board after k steps.
double ans = 0.0;
for (double[] row: dp) {
// just sum up all the probabilities in the board, that's the probability that knight will remain on the board.
for (double x: row) ans += x;
}
return ans;
}
}
BFS
这道题我一开始想的是用bfs. 创建一个class存概率和位置. 然后把这个class push到queue里运行bfs循环. 我觉得这么做也可以, 但是一开始懒得找8个方向就没写. 而且这个效率应该在8^k, 可能会爆炸. 因为一旦k move太多, 最后queue就存不下了.