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}};
};
相关文章
相关标签/搜索