Out of Boundary Paths

MediumDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A ball starts at cell [startRow, startColumn] of an m x n grid. In one move it steps to one of the four adjacent cells, and it may step off the grid, which ends that path. The ball may make **at most** maxMove moves. Return the number of distinct move sequences that take the ball off the grid. Two sequences are different if they differ in any move. Since the count can be huge, return it modulo 10^9 + 7.

Examples

Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6
Two single moves exit immediately (up, left), and four two-move sequences exit after first stepping right or down.
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
The middle cell of a 1x3 strip can exit up or down in one move, and more ways open with extra moves.

Constraints

  • `1 <= m, n <= 50`
  • `0 <= maxMove <= 50`
  • `0 <= startRow < m`
  • `0 <= startColumn < n`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems