LeetCode 576. Out of Boundary Paths

本文探讨了在一个m*n的网格中,从指定起点出发,球可以向四个方向移动并可能跨出边界的问题。通过动态规划算法,计算出在限定步数内,球能跨出网格边界的路径数量。考虑到答案可能非常大,最终结果会取模10^9+7。

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:

out_of_boundary_paths_1.png

Note:

  • Once you move the ball out of boundary, you cannot move it back.
  • The length and height of the grid is in range [1,50].
  • N is in range [0,50].

分析

动态规划

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        if(N==0) return 0;
        uint t=pow(10,9);
        vector<vector<uint>> dp(m,vector<uint>(n,0));
        for(int step=1;step<=N;step++){
            vector<vector<uint>> temp(m,vector<uint>(n,0));
            for(int p=0;p<m;p++)
                for(int q=0;q<n;q++){
                    if(p!=0)
                       temp[p][q]+=dp[p-1][q];
                    else
                       temp[p][q]++;
                    if(p!=m-1)
                       temp[p][q]+=dp[p+1][q];
                    else
                       temp[p][q]++;
                    if(q!=0)
                       temp[p][q]+=dp[p][q-1];
                    else
                       temp[p][q]++;
                    if(q!=n-1)
                       temp[p][q]+=dp[p][q+1];
                    else
                       temp[p][q]++;
                    temp[p][q]=temp[p][q]%(1000000007);
                }
          dp=temp;
        }
        return dp[i][j];
    }
};

转载于:https://www.cnblogs.com/A-Little-Nut/p/10074022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值