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.
{{2,-1},{2,1},{1,2},{1,-2},{-1,2},{-1,-2},{-2,1},{-2,-1}};

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.

Hint:
题目要我们求出 从(r,c)出发,走K步,骑士还在棋盘上的概率。
注意到这样一个事实:
从(r,c)出发,走K步,落在棋盘上的(i,j)点 意味着 从(i,j)出发,走K步,可落在(r,c)上。
这样我们可以把问题变成:
从棋盘的任意一点出发,走K步到达(r,c)点的概率和。
因此,走K步到达(r,c)的概率 = (走K-1步到达(r,c)可到的八个点的概率和/8)

注意要在每次计算时除8,因为周围的点到(i,j)只有1/8的概率。且必须在每次计算时就除,如果在最后才除pow(8,K),在前面的加法可能溢出。

class Solution {
private:
    int move[8][2] = {{2,-1},{2,1},{1,2},{1,-2},{-1,2},{-1,-2},{-2,1},{-2,-1}};
public:
    double knightProbability(int N, int K, int r, int c) {
        vector<vector<double> > dp(N, vector<double>(N,1));
        int row,col;
        for(int t = 0; t < K; t++) {
            vector<vector<double> > temp(N, vector<double>(N,0));
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    for (int k = 0; k < 8; k++) {
                        row = i+move[k][0];
                        col = j+move[k][1];
                        if (row < 0 || row >= N || col < 0 || col >= N) {
                            continue;
                        } else {
                            temp[i][j] += dp[row][col]/8.0;
                        }
                    }
                }
            }
            dp = temp;
        }
        return dp[r][c];
    }
};

猜你喜欢

转载自blog.csdn.net/ulricalin/article/details/79039824
今日推荐