[LeetCode] 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 次或跳到了棋盘外面。

求移动结束后,“马” 仍留在棋盘上的概率。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/knight-probability-in-chessboard
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是LC为数不多的题设是在棋盘上的题,另一道是1197题,可以放在一起做。因为棋盘类的题问的无非是能不能跳到某个特定的点或者能不能在一定的条件下跳到某个位置。这道题考的是马在跳了K步之后是否还能留在棋盘上。

我这里暂时先提供一个DFS + memo的思路。因为这道题问的是跳了K步之后的结果,所以只能是DFS,因为每一步之后马能跳的可能性是从上一步跳完之后得出的。用memo的用意在于需要记录在某一个位置上,在某个特定的步数K的时候,马有没有访问过。因为有八种可能性,马只会去其中一种,所以要乘以0.125。

时间O(K*n^2)

空间O(n^3)

Java实现

 1 class Solution {
 2     double[][][] memo;
 3     int[] dx = new int[] {-2, -2, -1, -1, 1, 1, 2, 2};
 4     int[] dy = new int[] {1, -1, 2, -2, 2, -2, 1, -1};
 5 
 6     public double knightProbability(int n, int k, int row, int column) {
 7         memo = new double[n + 1][n + 1][k + 1];
 8         return dfs(n, row, column, k);
 9     }
10 
11     private double dfs(int n, int r, int c, int k) {
12         // 越界的话,留在棋盘上的几率就是0
13         if (r < 0 || r >= n || c < 0 || c >= n) {
14             return 0.0;
15         }
16 
17         if (memo[r][c][k] != 0.0) {
18             return memo[r][c][k];
19         }
20         // 如果走完k步没有越界,几率就是100%
21         if (k == 0) {
22             return 1.0;
23         }
24         double res = 0.0;
25         for (int i = 0; i < 8; i++) {
26             int newR = r + dx[i];
27             int newC = c + dy[i];
28             res += 0.125 * dfs(n, newR, newC, k - 1);
29         }
30         memo[r][c][k] = res;
31         return res;
32     }
33 }

 

LeetCode 题目总结

posted @ 2020-11-09 02:28  CNoodle  阅读(260)  评论(0编辑  收藏  举报