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 mostmaxMove 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 modulo109 + 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
Solutions
Solution 1: Memoization Search
We define a function \(\textit{dfs}(i, j, k)\) to represent the number of paths that can move out of the boundary starting from coordinates \((i, j)\) with \(k\) steps remaining.
In the function \(\textit{dfs}(i, j, k)\), we first handle the boundary cases. If the current coordinates \((i, j)\) are out of the grid range, return \(1\) if \(k \geq 0\), otherwise return \(0\). If \(k \leq 0\), it means we are still within the grid but have no remaining moves, so return \(0\). Next, we iterate over the four directions, move to the next coordinates \((x, y)\), then recursively call \(\textit{dfs}(x, y, k - 1)\), and accumulate the results to the answer.
In the main function, we call \(\textit{dfs}(startRow, startColumn, maxMove)\), which represents the number of paths that can move out of the boundary starting from the initial coordinates \((\textit{startRow}, \textit{startColumn})\) with \(\textit{maxMove}\) steps remaining.
To avoid redundant calculations, we can use memoization.
The time complexity is \(O(m \times n \times k)\), and the space complexity is \(O(m \times n \times k)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, and \(k\) is the number of steps that can be moved, with \(k = \textit{maxMove} \leq 50\).