Out Of Boundary Paths Problem
Description
LeetCode Problem 576.
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.
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
Solution
Approach: Dynamic Programming Over Moves
Trying every sequence of moves takes O(4maxMove) time. But a path's future depends only on where the ball is and how many moves have been made, so we can count paths cell by cell instead of listing them.
Let ways[r][c] be the number of distinct paths that put the ball on cell (r, c) after the moves made so far. At the start, ways[startRow][startColumn] = 1 and every other cell is 0.
Then repeat maxMove times:
- Create an empty grid
nextWays. - For every cell with
ways[r][c] > 0, try the four directions. If the neighbor is inside the grid, addways[r][c]tonextWaysat that neighbor. If it is outside, thoseways[r][c]paths leave the grid on this move: add them to the answer. - Replace
wayswithnextWays.
A path that leaves the grid stops there, so it is counted exactly once, on the move that takes it out. Paths that are still inside after maxMove moves are never counted. Take every sum modulo 109 + 7, because the counts grow exponentially. With maxMove = 0 the loop never runs and the answer is 0.
Complexity: O(maxMove · m · n) time and O(m · n) space for the two grids.
class Solution:
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
MOD = 10**9 + 7
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# ways[r][c] = number of paths that end at (r, c) after the moves made so far
ways = [[0] * n for _ in range(m)]
ways[startRow][startColumn] = 1
out_paths = 0
for _ in range(maxMove):
next_ways = [[0] * n for _ in range(m)]
for r in range(m):
for c in range(n):
if ways[r][c] == 0:
continue
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
next_ways[nr][nc] = (next_ways[nr][nc] + ways[r][c]) % MOD
else:
out_paths = (out_paths + ways[r][c]) % MOD # this move leaves the grid
ways = next_ways
return out_paths
Now write it from memory
Close the write-up and solve it yourself against the tests.