101 Logo
onenoughtone

Problem Statement

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.

Examples

Example 1:

Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6
Explanation: There are 6 paths moving the ball out of the grid boundary. From starting position, there are 2 ways to move out in 1 step (moving up or left). From starting position, there are 4 ways to move out in 2 steps (moving right then up, right then left, down then left, down then up).

Example 2:

Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
Explanation: There are 12 paths moving the ball out of the grid boundary.

Constraints

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

Problem Breakdown

To solve this problem, we need to:

  1. This problem can be solved using dynamic programming with a 3D DP array.
  2. The state of the DP array is defined by the current position (row, column) and the number of moves remaining.
  3. For each state, we need to consider all four possible directions to move the ball.
  4. We need to handle the modulo operation carefully to avoid integer overflow.
  5. The base case is when the ball is out of the grid boundary, which contributes 1 to the count.
ProblemSolutionCode
101 Logo
onenoughtone