Leetcode算法学习日志-576 Out of Boundary Paths

Leetcode 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].

题意分析

球只能往上下左右四个方向走,走到范围外并且步数没有超过N就停止,并算一次成功的Path,走一步可以往回走。

解法分析

本题采用动态规划方法,先寻找递归式,令剩余N步,坐标为i,j时Path总数为T(N,i,j),则T(N,i,j)=T(N-1,i,j-1)+T(N-1,i,j+1)+T(N-1,i+1,j)+T(N-1,i-1,j),此种递归式适合用自底向上的动态规划方法,N从1到N,i从0到m-1,j从0到n-1,由于只有变量N是递增的,所以N作为外层循环变量,可以保证求一个T(N,i,j)所需的所有条件都在他之前求出。C++代码如下:

class Solution {
public:

    int findPaths(int m, int n, int N, int i, int j) {
        int M=1000000007;
       vector<vector<vector<unsigned int>>> count(N+1,vector<vector<unsigned int>>(m,vector<unsigned int>(n,0)));
        //uint count[51][50][50];
        int q,p,r;
        for(q=1;q<=N;q++){
            for(p=0;p<m;p++){
                for(r=0;r<n;r++){
                    count[q][p][r]=((p==0?1:count[q-1][p-1][r])%M+(p==m-1?1:count[q-1][p+1][r])%M+(r==0?1:count[q-1][p][r-1])%M+(r==n-1?1:count[q-1][p][r+1])%M)%1000000007;
                }
            }
        }
        return count[N][i][j];
         
    }
};
这道题所求值可能超过int的范围,所以应用unsigned int。做此类题时,自底向上能用多维数组存储的就用多维数组,用vector表示多维数组较慢,如果限定了数组的最大大小,可以采用静态数组,规定大小,如果不能确定大小范围,则采用动态数组或者vector。本题不建议采用自顶向下的带存储递归方法,原因是递归函数参数多,调用开销大。

对于递归式中的递增变量,如此题的N,由于每次计算只需要前一次的值,所以不需要对每次的值都进行存储,优化的C++代码如下:

vector<vector<vector<unsigned int>>> count(2,vector<vector<unsigned int>>(m,vector<unsigned int>(n,0)));
N变量值需要二维,大大节约了空间。算法复杂度为O(N*m*n)。

代码中设计的C++知识如下:

  • 三维的vector初始化方法如下:
    vector<vector<vector<unsigned int>>> count(N+1,vector<vector<unsigned int>>(m,vector<unsigned int>(n,0)));
  • 定义数组时值随机的,如想初始化为0需要int count[10][20]={},{}内写0也可以。
  • 代码中count[q][p][r]的求法灵活使用了?:运算符。
  • 定义三维动态数组比较麻烦,代码如下

	int ***a = new int **[m];
	for (i = 0; i<n; i++) {
		a[i] = new int *[n];
		for (j = 0; j<n; j++)
			a[i][j] = new int[o];
	}
上述代码得到一个三维数组a[m][n][o]。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值