LeetCode 576 Out of Boundary Paths (记忆化搜索)

177 篇文章 0 订阅
66 篇文章 0 订阅

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent four cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

Given the five integers mnmaxMovestartRowstartColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

 

Example 1:

Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6

Example 2:

Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12

 

Constraints:

  • 1 <= m, n <= 50
  • 0 <= maxMove <= 50
  • 0 <= startRow <= m
  • 0 <= startColumn <= n

题目链接:https://leetcode.com/problems/out-of-boundary-paths/

题目大意:求球通过maxMove步被移出区域的方案数

题目分析:很容易想到记忆化搜索,dp[i][j][k]表示到点(i, j)还剩k步时将球移除的方案数,于是上下左右记忆化搜索就好,然后会得到一个TLE,这里有一个关键且不难想的剪枝,当还剩k步,但此时球到四个边界的距离均大于等于k时其必不可能被移出去,返回0即可

2ms,时间击败100%

class Solution {
    
    public int MOD = 1000000007;
    
    public int dfs(int[][][] dp, int x, int y, int N, int m, int n) {
        if (x >= m || y >= n || x < 0 || y < 0) {
            return 1;
        }
        if (x >= N && y >= N && m - x > N && n - y > N) {
            return 0;
        }
        if (dp[x][y][N] != 0) {
            return dp[x][y][N];
        }
        
        if (N > 0) {
            dp[x][y][N] = (dp[x][y][N] + dfs(dp, x - 1, y, N - 1, m, n)) % MOD;
            dp[x][y][N] = (dp[x][y][N] + dfs(dp, x + 1, y, N - 1, m, n)) % MOD;
            dp[x][y][N] = (dp[x][y][N] + dfs(dp, x, y - 1, N - 1, m, n)) % MOD;
            dp[x][y][N] = (dp[x][y][N] + dfs(dp, x, y + 1, N - 1, m, n)) % MOD;
        }
        return dp[x][y][N];
    }
    
    public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
        int[][][] dp = new int[m][n][maxMove + 1];
        dfs(dp, startRow, startColumn, maxMove, m, n);
        return dp[startRow][startColumn][maxMove] % MOD;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值