LeetCode 576. Out of Boundary Paths C++

576. 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.

Example 1:

Input:m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6

Explanation:
这里写图片描述
Example 2:

Input:m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12

Explanation:
这里写图片描述
Note:
1. Once you move the ball out of boundary, you cannot move it back.
2. The length and height of the grid is in range [1,50].
3. N is in range [0,50].

Approach

  1. 题目大意是一个球移动不多于N次,能走出边界的有多少种走法,很明显是要用动态规划处理,否则超时,这里我采用记忆化搜索,动态规划的另一种写法,这道题其实也不难,我用一个三维数组res[N][i][j]记忆表示当这个球已移动N次,在坐标为ij的状态下有多少种走法,现在我们来讨论一下该怎么搜索,因为没有障碍,所以我们要搜索球移动上下左右,然后边界很明显就是当ij到达矩阵的边界,还有就是已经移动了N次。
  2. 多练多想多看,就容易有思路,多看不同的写法,有时是可以猜状态转移方程的。

Code

class Solution {
public:
    int mod = 1000000007;
    int findPaths(int m, int n, int N, int i, int j) {
        vector<vector<vector<int>>>res(N+1, vector<vector<int>>(m, vector<int>(n, -1)));
        return DFS(res,m, n, N, i, j);
    }
    int DFS(vector<vector<vector<int>>> &res, int m, int n, int N, int i, int j) {
        if (i<0 || j<0 || i >= m || j >= n) {
            return 1;
        }
        if (N <= 0)return 0;
        if (res[N][i][j] != -1)return res[N][i][j]%mod;
        res[N][i][j] = (((DFS(res, m, n, N - 1, i + 1, j)%mod + DFS(res, m, n, N - 1, i, j + 1))%mod + DFS(res, m, n, N - 1, i - 1, j))%mod + DFS(res, m, n, N - 1, i, j - 1))%mod;
        return res[N][i][j]%mod;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值