Out of Boundary Paths - Problem
Out of Boundary Paths - Find the number of ways a ball can escape from a grid

Imagine you have a ball placed on an m × n grid at position [startRow, startColumn]. The ball can move in four directions (up, down, left, right) to adjacent cells, and importantly, it can also move outside the grid boundaries to escape!

You're given a maximum of maxMove moves to work with. Your task is to count all possible paths that lead the ball out of the grid boundary within the move limit.

Key Points:
• The ball starts at [startRow, startColumn]
• Each move allows the ball to go to any adjacent cell (including out of bounds)
• Moving out of bounds counts as an escape path
• You can use at most maxMove moves
• Return the count modulo 10^9 + 7

Example: In a 2×3 grid starting at [0,1] with 2 moves, the ball could escape by going up (1 move) or left then up (2 moves), among other paths.

Input & Output

example_1.py — Small Grid
$ Input: [2, 3, 3, 0, 1]
Output: 12
💡 Note: In a 2×3 grid starting at [0,1] with 3 moves, there are 12 different paths that lead the ball out of the grid boundary. The ball can escape by moving up (1 move), or various combinations of left/right then up/down.
example_2.py — Single Move
$ Input: [1, 3, 3, 0, 1]
Output: 12
💡 Note: In a 1×3 grid starting at [0,1] with 3 moves, the ball is in the middle column. It can escape up or down in 1 move, or move left/right first then escape. Multiple paths exist due to the move flexibility.
example_3.py — No Escape
$ Input: [10, 10, 0, 5, 5]
Output: 0
💡 Note: With 0 moves allowed, the ball cannot move at all, so there are 0 paths to escape the grid boundary.

Constraints

  • 1 ≤ m, n ≤ 50
  • 0 ≤ maxMove ≤ 50
  • 0 ≤ startRow < m
  • 0 ≤ startColumn < n
  • Answer must be returned modulo 109 + 7

Visualization

Tap to expand
Out of Boundary Paths - Ball EscapeGrid Boundary (m×n)BallStart: [1,2]Escape!Escape!Escape!Escape!Brute ForceO(4^maxMove)Explores all pathsVery slow!MemoizationO(m×n×maxMove)Cache resultsOptimal!Key InsightSame (row,col,moves)= Same result→ Memoize it!
Understanding the Visualization
1
Setup
Place ball at starting position [startRow, startColumn] on m×n grid
2
Explore Moves
From each position, ball can move up, down, left, or right
3
Count Escapes
Moving out of grid boundaries counts as one escape path
4
Memoize
Cache results for each (row, col, moves) state to avoid recalculation
5
Sum Paths
Total all possible escape paths within move limit
Key Takeaway
🎯 Key Insight: The number of escape paths from any position depends only on current coordinates and remaining moves - making this perfect for memoization to avoid exponential recalculation!
Asked in
Google 28 Amazon 22 Facebook 18 Microsoft 15
58.0K Views
Medium Frequency
~25 min Avg. Time
1.5K 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