Parcel-delivery app~15 min2s · 256 MBtarget O(down × right) time, O(down × right) spacedp
A parcel-delivery app sends a small robot along a street grid. The robot moves one block down or one block right, and it must end at the far corner.
The route planner counts the different routes with a recursion. It is slow, because the same corner is reached again and again.
Your team lead says: Count the routes, and also tell me how many calls the recursion makes with and without a cache.
Write route_report(down, right).
down blocks and right blocks from the far corner. Each move goes one block down or one block right.down - 1, and one with right - 1. A call with down = 0 or right = 0 makes no more calls, and counts one route.down = 0 or right = 0 is never stored.Input: down = 2, right = 2
Output: [6, 11, 9]For a 2 by 2 grid, the cached recursion solves each pair of distances once. The calls are made in this order.
| Call | Pair of distances | What happens |
|---|---|---|
| 1 | (2, 2) | not stored, so it makes two calls |
| 2 | (1, 2) | not stored, so it makes two calls |
| 3 | (0, 2) | a straight line: 1 route |
| 4 | (1, 1) | not stored, so it makes two calls |
| 5 | (0, 1) | a straight line: 1 route |
| 6 | (1, 0) | a straight line: 1 route |
| 7 | (2, 1) | not stored, so it makes two calls |
| 8 | (1, 1) | stored: returns 2 at once |
| 9 | (2, 0) | a straight line: 1 route |
There are 6 routes. The plain recursion makes 11 calls, and the cached one makes 9. The answer is [6, 11, 9].
Input: down = 0, right = 5
Output: [1, 1, 1]On a straight line there is one route, and the first call returns at once. The answer is [1, 1, 1].
Input: down = 3, right = 3
Output: [20, 39, 19]A 3 by 3 grid has 20 routes. The plain recursion makes 39 calls, and the cached one makes 19.
0 ≤ down ≤ 250 ≤ right ≤ 25A 25 by 25 grid has 126,410,606,437,752 routes, and the plain recursion makes 252,821,212,875,503 calls. Running it is not possible, so the plain call count must come from a rule. The cached recursion makes 1,251 calls. Every number is below 2^53, so it is exact in every language.