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].
给定最多的移动次数,将小球移出矩形区域,求可能的移动次数。小球移出区域后不能在进入矩形区域。

我的思路:

1、写出递归方法,比较容易想  TLE

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        if(N>=0&&(i==-1||j==-1||i==m||j==n))
            return 1;
        else if(N==0) return 0;
        int sum=0;
        sum+=findPaths(m,n,N-1,i-1,j)+findPaths(m,n,N-1,i+1,j)+findPaths(m,n,N-1,i,j-1)+findPaths(m,n,N-1,i,j+1);
        return sum%(1000000007);
    }
};

2、改成存储版本得动态规划

递归函数的变量有N,i,j三个。将计算过得都存储起来.

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
         vector<vector<vector<int>>> dp(N+1,vector<vector<int>>(m,vector<int>(n,-1)));//建立初始化动态规划数组全部是-1.因为0代表没有解决方案
        return find(m,n,N,i,j,dp);
    }
   
    int find(int m, int n, int N, int i, int j,vector<vector<vector<int>>>& dp)
    {
       
        if(i==-1||j==-1||i==m||j==n)
           {
              return 1;
           } 
        if(N==0) 
            return 0;
        if(dp[N][i][j]>=0) return dp[N][i][j];//需要在后面判断,因为可能是越界的
        dp[N][i][j]=(((find(m,n,N-1,i-1,j,dp)+find(m,n,N-1,i+1,j,dp))%M+find(m,n,N-1,i,j-1,dp))%M+find(m,n,N-1,i,j+1,dp))%M;//这种取模的情况要把所有的加和后面都取模
        return dp[N][i][j];
    }
   int M=1000000007;
};

3、递归版本


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值