[DP] 576Out of boundary path

本文介绍了一种使用动态规划解决网格路径问题的方法。通过计算从四个方向到达每个格子的路径数量来递推求解,最终得出从指定起点出发到达边界路径总数的算法实现。

题意不再赘述,大致解法是用动态规划。
N等于来自于4个方向N-1的解的和

Solution

方案:

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        int dp[51][50][50];
        for(int Ni=1;Ni<=N;Ni++){
            for (int mi=0;mi<m;mi++){
                for(int ni=0;ni<n;ni++){
                    dp[Ni][mi][ni] = ((long long)(!mi?1:dp[Ni-1][mi-1][ni]) + (mi==m-1?1:dp[Ni-1][mi+1][ni])
                                                +(!ni?1:dp[Ni-1][mi][ni-1]) + (ni==n-1?1:dp[Ni-1][mi][ni+1]))%1000000007;
                }
            }
        }
        return dp[N][i][j];
    }
 };
Tips

需要注意的是:题目中提示数会很大,所以需要long long转化一下,并且是从第一个数开始long long,否则会出现莫名的错误。
利用三目运算符的简洁。

Description You are given an n × m n×m grid having an integer in each cell of the grid. A little bear wants to walk from the top left corner to the bottom right corner of the grid. In each step, the bear can only move one cell up, down or right. It can't go to a cell that it has already visited earlier, and it can't go out of the boundary of the grid. The bear will calculate the sum of integers in all the squares it walks through. Find the maximum sum of integers it can obtain. Input Format The first line contains two integers n n and m m. i i-th of the next n n lines contains m m integers, which represent the integers in the i i-th row of the grid. Output Format Print a single integer denoting the maximum sum of integers the bear can obtain. 输入数据 1 3 4 1 -1 3 2 2 -1 4 -1 -2 2 -3 -1 输出数据 1 9 Taking the first path in the image below gives a sum of 9, which is the maximum possible. The second path is invalid because the cell in row 2 and column 2 has been visited twice, which is not allowed. The third path is also invalid, because it does not end at the bottom right corner. 输入数据 2 2 5 -1 -1 -3 -2 -7 -2 -1 -4 -1 -2 输出数据 2 -10 Taking the path shown in the image below gives a sum of -10, which is the maximum possible. Therefore, the maximum value of the sum may also be negative. Constraints For 20 % 20% of the data, n , m ≤ 5 n,m≤5. For 40 % 40% of the data, n , m ≤ 50 n,m≤50. For 70 % 70% of the data, n , m ≤ 300 n,m≤300. For 100 % 100% of the data, 1 ≤ n , m ≤ 10 3 1≤n,m≤10 3 . The absolute value of each integer in the grid doesn't exceed 10 4 10 4 .C++
最新发布
11-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值