Ctrl K

Ball Escape Routes

Medium
A board has rows × cols cells, and a ball sits on cell (row, col). In one move the ball rolls to the neighbouring cell up, down, left or right; if there is no such cell, the ball flies off the board and its route ends there. Count the distinct sequences of moves that take the ball off the board using at most moves moves. The answer can be huge, so return it modulo 10⁹ + 7.
Example 1
rows=1, cols=1, moves=2, row=0, col=0 → 4

From the only cell, the ball leaves the board on its first move in any of the 4 directions; it can never come back.

Example 2
rows=2, cols=3, moves=2, row=0, col=1 → 6

One way out right away: up. In two moves: first left or right (2 exits from each), or down (1 exit from there), giving 1 + 2 + 2 + 1 = 6.

Example 3
rows=3, cols=3, moves=1, row=1, col=1 → 0

From the centre, one move cannot reach the edge.

Constraints
  • 1 ≤ rows, cols ≤ 50
  • 0 ≤ moves ≤ 50
  • 0 ≤ row < rows
  • 0 ≤ col < cols
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumAll Balanced Bracket Strings MediumFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell Medium
loading Python…
Input
rows=1, cols=1, moves=2, row=0, col=0
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 120 tests on the server, hidden ones included.