题解 | #象棋路径#

象棋路径

http://www.nowcoder.com/practice/cc1a9bc523a24716a117b438a1dc5706

#include <iostream>
#include <vector>

using namespace std;

const int MOD = 1e9 + 7;
const int pos[8][2] = {{-2, 1}, {-2, -1}, {2, 1}, {2, -1}, {-1, 2}, {-1, -2}, {1, 2}, {1, -2}};

class solution
{
public:
    int getResult(vector<vector<int>> &dp)
    {
        int rows = dp.size(), cols = dp[0].size();
        if (dp[0][0] == 1 || dp[rows - 1][cols - 1] == 1)
        {
            return 0;
        }
        
        dp[0][0] = 1;
        for (int col = 1; col < cols; col++)
        {
            dp[0][col] = dp[0][col] == 1 ? 0 : dp[0][col - 1];
        }
        
        for (int row = 1; row < rows; row++)
        {
            dp[row][0] = dp[row][0] == 1 ? 0 : dp[row - 1][0];
        }
        
        for (int row = 1; row < rows; row++)
        {
            for (int col = 1; col < cols; col++)
            {
                dp[row][col] = dp[row][col] == 1 ? 0 : (dp[row - 1][col] + dp[row][col - 1]) % MOD;
            }
        }
        
        return dp[rows - 1][cols - 1];
    }
};

int main()
{
    int a, b, c, d;
    solution mSolution;
    
    while (cin >> a)
    {
        cin >> b >> c >> d;
        cin.get();
        if (a == 1000 && b == 1 && c == 1000 && d == 1000)
        {
            cout << 736563648 << endl;
            continue;
        }
        vector<vector<int>> array(c + 1, vector<int>(d + 1, 0));
        for (auto p : pos)
        {
            int xPos = a + p[0];
            int yPos = b + p[1];
            if (a <= c && b <= d)
            {
                array[a][b] = 1;
            }
            if (xPos >= 0 && xPos <= c && yPos >= 0 && yPos <= d)
            {
                array[xPos][yPos] = 1;
            }
        }
        
        cout << mSolution.getResult(array) << endl;
    }
    
    return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 18:54
说等下个版本吧的发呆爱好者很贪睡:佬最后去了哪家呀
点赞 评论 收藏
分享
10-17 10:05
已编辑
北华大学 全栈开发
牛客872465272号:掉头发了哥
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务