Payments app~30 min2s · 256 MBtarget O(routes × degree) time, O(n) spacedfs · backtracking
A cross-border payments app can convert money from one currency to another through partner corridors. A corridor links two currencies in one direction and charges a fixed fee in units.
A customer wants to know how many different routes lead from the currency they hold to the currency they need. A route may not use the same currency twice, it may have only a few hops, and its total fee must stay inside a budget.
Write count_routes(n, froms, tos, fees, start, goal, max_hops, budget).
0 to n - 1. Corridor i goes from froms[i] to tos[i] and costs fees[i] units. There is at most one corridor for each ordered pair, and none from a currency to itself.start to goal and visits no currency twice. start and goal are different.max_hops corridors and its fees add up to at most budget.Input: n = 5, froms = [0, 0, 1, 2, 1, 2, 0, 3, 2], tos = [1, 2, 2, 1, 4, 4, 3, 4, 3], fees = [3, 1, 1, 2, 2, 5, 4, 1, 1], start = 0, goal = 4, max_hops = 3, budget = 6
Output: 5Every route from currency 0 to currency 4 that repeats no currency:
| Route | Hops | Fee | Counted? |
|---|---|---|---|
| 0 to 1 to 4 | 2 | 5 | yes |
| 0 to 3 to 4 | 2 | 5 | yes |
| 0 to 2 to 4 | 2 | 6 | yes |
| 0 to 2 to 3 to 4 | 3 | 3 | yes |
| 0 to 2 to 1 to 4 | 3 | 5 | yes |
| 0 to 1 to 2 to 4 | 3 | 9 | no: over budget |
| 0 to 1 to 2 to 3 to 4 | 4 | 6 | no: too many hops |
Seven routes reach currency 4. Two of them break a limit: the first has too high a fee, the second too many hops. Five routes count, so the output is 5.
Input: n = 3, froms = [0, 1, 1], tos = [1, 0, 2], fees = [0, 0, 0], start = 0, goal = 2, max_hops = 5, budget = 0
Output: 1The corridors between currencies 0 and 1 form a cycle, but a route cannot visit a currency twice. The only route is 0, 1, 2, so the output is 1.
Input: n = 3, froms = [0, 1], tos = [1, 2], fees = [1, 1], start = 2, goal = 0, max_hops = 4, budget = 10
Output: 0Corridors only go forward, from 0 to 1 to 2, so nothing leads from currency 2 back to currency 0. The output is 0.
2 ≤ n ≤ 16 (currencies in the corridor network)1 ≤ froms.length ≤ 240; tos and fees have the same length, and 0 ≤ froms[i], tos[i] < n0 ≤ fees[i] ≤ 1,000 (units)0 ≤ start, goal < n, start ≠ goal1 ≤ max_hops ≤ 8 and 0 ≤ budget ≤ 100,000 (units)These limits are small because the answer counts routes, and a dense network has millions of them. There is no formula to shortcut the count, so the search must visit routes. It must also stop early: a route that has used up its hops or its budget cannot grow, so it is abandoned at once. The count itself fits in a 32-bit integer.