A ball sits on cell (startRow, startColumn) of a grid with m rows and n columns. Each move pushes it one cell up, down, left or right. A move may carry it over the edge, and once it is off the grid it stays off.
Using at most maxMove moves, count the different move sequences that end with the ball leaving the grid. The count can be huge, so return it modulo 1,000,000,007.
Example 1
Input: m = 2, n = 3, maxMove = 2, startRow = 0, startColumn = 1 Output: 6 Why: 1 path leaves on the first move, 5 more on the second
2 more examples and the constraints
Example 2
Input: m = 3, n = 3, maxMove = 1, startRow = 1, startColumn = 1 Output: 0 Why: one move only reaches an edge cell; leaving takes two
Example 3
Input: m = 1, n = 1, maxMove = 4, startRow = 0, startColumn = 0 Output: 4 Why: every first move leaves; nothing is left to count
Constraints
- The grid has between 1 and 50 rows, and between 1 and 50 columns
- maxMove is between 0 and 50
- The start cell is inside the grid
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(k·m·n)
- Spread counts move by moveO(k·m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 grid, 50 moves | Verdict |
|---|---|---|---|
| Recursion with a memo | O(k·m·n) | Correct; memo and calls cost | |
| Spread counts move by move | O(k·m·n) | Best; two small grids |
k = maxMove, m and n = grid rows and columns.
Edge cases to test
- No moves allowed. maxMove = 0 means the ball never leaves: return 0.
- A 1 × 1 grid. Every first move leaves, giving 4; after that nothing is left on the grid.
- Start far from the edge. On a big grid with few moves, the ball may not reach the edge: the answer is 0.
- Huge counts. Take the modulo on every addition, not only at the end, or the numbers overflow.
Common mistakes
- Counting only paths that use exactly maxMove moves, instead of leaving at any move up to it.
- Letting a path keep moving after it leaves the grid; once off, it is finished.
- Updating
waysin place during a move, so a count moves twice in the same round.
How to talk through it
- 1Clarify. Is it at most maxMove moves? Once the ball leaves, does that path stop?
- 2Name the state. What matters is the cell and the moves left, so there are m·n·(maxMove + 1) states.
- 3Start with a memo. count(r, c, k) adds the four neighbours with k − 1; off the grid is 1.
- 4Go bottom up. Keep a grid of path counts per move and spread it; counts that step off go into out.
- 5Test out loud. Try maxMove = 0, a 1 × 1 grid, and a start that cannot reach the edge.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?