leetcode 576. Out of Boundary Paths 、688. Knight Probability in Chessboard

576. Out of Boundary Paths html

https://www.cnblogs.com/grandyang/p/6927921.htmlc++

dp表示上一次移動,全部位置的路徑數;t表示的是當前移動,全部位置的路徑數。而後每次用t去更新dp,即當前次移動去更新上一次移動。spa

每次只要超過了邊界,就記錄可能的路徑數更新最終的結果。code

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        int res = 0;
        vector<vector<int>> dp(m,vector<int>(n,0));
        dp[i][j] = 1;
        for(int k = 0;k < N;k++){
            vector<vector<int>> tmp(m,vector<int>(n,0));
            for(int r = 0;r < m;r++){
                for(int c = 0; c < n;c++){
                    for(auto dir:dirs){
                        int x = r + dir[0];
                        int y = c + dir[1];
                        if(x < 0 || x >= m || y < 0 || y >= n)
                            res = (res + dp[r][c])% 1000000007;
                        else
                            tmp[x][y] = (tmp[x][y] + dp[r][c])% 1000000007;
                    }
                }
            }
            dp = tmp;
        }
        return res;
    }
private:
    vector<vector<int>> dirs{{-1,0},{1,0},{0,-1},{0,1}};
};

688. Knight Probability in Chessboardhtm

https://www.cnblogs.com/grandyang/p/7639153.htmlblog

https://www.cnblogs.com/Dylan-Java-NYC/p/7633409.htmlit

求最後在board上的機率. 反過來想,走完K步棋子在board上的哪一個位置呢. 反過來走, 看board上全部位置走完K步後能到初始位置(r,c)的數目和。io

這個題必須用double纔不會越界,有點搞不懂爲何。class

class Solution {
public:
    double knightProbability(int N, int K, int r, int c) {
        vector<vector<double>> dp(N,vector<double>(N,1));
        for(int k = 0;k < K;k++){
            vector<vector<double>> tmp(N,vector<double>(N,0));
            for(int i = 0;i < N;i++){
                for(int j = 0;j < N;j++){
                    for(auto dir :dirs){
                        int x = i + dir[0];
                        int y = j + dir[1];
                        if(x < 0 || x >= N || y < 0 || y >= N)
                            continue;
                        else
                            tmp[x][y] += dp[i][j];
                    }
                }
            }
            dp = tmp;
        }
        return dp[r][c]/pow(8,K);
    }
private:
    vector<vector<int>> dirs{{-1,2},{1,2},{-1,-2},{1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};
};
相關文章
相關標籤/搜索