There is an m x n grid with a ball. The ball starts at the position [startRow, startColumn]. You may move the ball to one of the four adjacent cells (up, down, left or right), and a move can take it across the grid boundary and out of the grid. You can apply at most maxMove moves to the ball.
Given the five integers m, n, maxMove, startRow and startColumn, return the number of paths that move the ball out of the grid boundary. Since the answer can be very large, return it modulo 10⁹ + 7.
Function Signature
def find_paths(m: int, n: int, max_move: int, start_row: int, start_column: int) -> int:
Rules
-
A path is a sequence of moves. It ends the moment the ball leaves the grid, so a ball that has left never comes back.
-
A path counts when the ball leaves the grid on its last move and the path uses at most
max_move
moves. Paths of different lengths are all counted.
-
Two paths are different when their sequences of moves differ.
-
Rows are numbered 0 to
m - 1
and columns 0 to
n - 1
.
Constraints
-
1 <= m, n <= 50
-
0 <= maxMove <= 50
-
0 <= startRow < m
-
0 <= startColumn < n
Examples
Input: m = 2, n = 2, max_move = 2, start_row = 0, start_column = 0
Output: 6
From the corner, the ball can leave at once by moving up or left (2 paths). It can also step right to (0, 1) and then leave up or right (2 paths), or step down to (1, 0) and then leave down or left (2 paths), for 6 in total.
Input: m = 1, n = 3, max_move = 3, start_row = 0, start_column = 1
Output: 12
From the middle cell of a single row, 2 paths leave in one move (up or down), 6 paths leave in two moves (step to an end cell, then take one of its 3 exits) and 4 paths leave in three moves (step to an end cell, step back to the middle, then exit up or down). That gives 2 + 6 + 4 = 12.
Input: m = 3, n = 3, max_move = 2, start_row = 1, start_column = 1
Output: 4
The center cell has no exit of its own, so every path first steps to one of the 4 edge-middle cells, and each of those has exactly one exit.