Out of Boundary Paths

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 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 m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo $10^9 + 7$.

Problem Image 1

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

Problem Image 2

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

Constraints

  • $1 \leq m, n \leq 50$
  • $0 \leq maxMove \leq 50$
  • $0 \leq startRow < m$
  • $0 \leq startColumn < n$

题目分析

DFS | DP

代码实现

DFS (TLE)

const int N = 1e2;
class Solution {
public:
    int dp[N][N];
    int findPaths(int n, int m, int maxMove, int x, int y) {
        if(x < 0 || y < 0 || x == n || y == m) return 1;
        if(!maxMove) return 0;
        return findPaths(m, n, maxMove - 1, x + 1, y) + 
               findPaths(m, n, maxMove - 1, x, y + 1) + 
               findPaths(m, n, maxMove - 1, x - 1, y) + 
               findPaths(m, n, maxMove - 1, x, y - 1);
    }
};

DFS | DP (AC)

const int N = 1e2, MOD = 1e9 + 7;
class Solution {
public:
    int dp[N][N][N], n, m;
    int solve(int maxMove, int x, int y) {
        if(x < 0 || y < 0 || x == n || y == m) return 1;
        if(!maxMove) return 0;
        if(dp[x][y][maxMove] != -1) return dp[x][y][maxMove]; 
        return dp[x][y][maxMove] = ((solve(maxMove - 1, x + 1, y) + 
                                solve(maxMove - 1, x, y + 1))
                                (solve(maxMove - 1, x - 1, y) + 
                                solve(maxMove - 1, x, y - 1))
    }
    int findPaths(int n, int m, int maxMove, int x, int y) {
        this->n = n, this->m = m;
        memset(dp, -1, sizeof dp);
        return solve(maxMove, x, y);
    }
};
分类: DP

0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

友情链接:Ctips' blog, Colza’s blog

站点状态:Status