Out of Boundary Paths

Out of Boundary Paths
There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.

class Solution {
private:
    static const int MOD_NUM = 1e9 + 7;
public:
    int findPaths(int m, int n, int N, int i, int j) {
        /*
         0 1 2 3 4 5 6 7
        0@ @ @ @ @ @ @ @
        1@ O O O O O O @
        2@ O O O O O O @
        3@ O O O O O O @
        4@ O O O O O O @
        5@ @ @ @ @ @ @ @
        */
        vector<vector<vector<int> > > num(m + 2, vector<vector<int>>(n + 2, vector<int>(N + 1, -1)));
        for (int k = 1; k <= N; ++k) { 
            this->findPathsInner(m, n, k, i + 1, j + 1, num);
        }
        int ret = 0;
        for (int k = 1; k <= N; ++k) {
            if (num[i + 1][j + 1][k] > 0) {
                //cout<<k<<"\t"<<num[i + 1][j + 1][k]<<endl;
                ret = (num[i + 1][j + 1][k] % MOD_NUM + ret % MOD_NUM) % MOD_NUM;
            }
        }
        return ret;
    }
    
    void findPathsInner(int m, int n, int N, int i, int j, vector<vector<vector<int> > >& num) {
        if (i <= 0 || j <= 0 || i > m || j > n) {
            if (N == 0) {
                num[i][j][N] = 1;
            } else {
                num[i][j][N] = 0;
            }
            return ;
        }
        
        //已经求出来了
        if (num[i][j][N]>=0) {
            return;
        }
        //没有到边界,已经走完了N步
        if (N == 0) {
            num[i][j][N] = 0;
            return;
        }
        //搜索
        this->findPathsInner(m, n, N - 1, i - 1, j, num);
        this->findPathsInner(m, n, N - 1, i, j - 1, num);
        this->findPathsInner(m, n, N - 1, i + 1, j, num);
        this->findPathsInner(m, n, N - 1, i, j + 1, num);
        
        num[i][j][N] = (((  num[i - 1][j][N - 1] % MOD_NUM 
                          + num[i + 1][j][N - 1] % MOD_NUM) % MOD_NUM 
                          + num[i][j - 1][N - 1] % MOD_NUM) % MOD_NUM
                          + num[i][j + 1][N - 1] % MOD_NUM) % MOD_NUM;
        return ;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值