Out of Boundary Paths - Problem

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 109 + 7.

Input & Output

Example 1 — Small Grid
$ Input: m = 2, n = 3, maxMove = 2, startRow = 1, startColumn = 1
Output: 6
💡 Note: From center position (1,1), the ball can exit the boundary in 6 different ways within 2 moves: moving up-up, up-left, up-right, down-down, down-left, down-right
Example 2 — Single Move
$ Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
💡 Note: From middle of 1x3 grid, ball can exit left or right in 1 move (2 ways), or make more complex paths using all 3 moves for total of 12 paths
Example 3 — No Moves
$ Input: m = 2, n = 2, maxMove = 0, startRow = 0, startColumn = 0
Output: 0
💡 Note: With 0 moves allowed, the ball cannot move at all, so there are 0 paths to exit the boundary

Constraints

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

Visualization

Tap to expand
Out of Boundary Paths INPUT 2x3 Grid with Ball B 0 1 0 1 2 m = 2, n = 3 maxMove = 2 startRow = 1 startColumn = 1 ALGORITHM (DP) 1 Define State dp[move][row][col] = paths 2 Base Case dp[0][start][start] = 1 3 Transition Sum paths from 4 dirs 4 Count Exits Add boundary crosses DP Transitions (move=1): 0 1 0 1 0 1 Green = reachable in 1 move Boundary exits: 2 (moves left) FINAL RESULT 6 Paths to Exit Boundary Path 1 Up-->Up Path 2 Up-->Left Path 3 Up-->Right Path 4 Down-->Down Path 5 Left-->Left Path 6 Right-->Right Output 6 [OK] Result verified mod 10^9 + 7 Key Insight: Use 3D DP where dp[k][i][j] represents paths to reach cell (i,j) in exactly k moves. For each cell at boundary, count exits when ball moves outside. Sum all boundary exits across all moves. TutorialsPoint - Out of Boundary Paths | Dynamic Programming Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen