Count All Possible Routes - Problem
Fuel-Constrained City Travel
Imagine you're planning a road trip across several cities with limited fuel! ๐โฝ
You're given an array
Travel Rules:
โข You can move from any city
โข Moving from city
โข You can revisit cities multiple times (including start and finish)
โข Your fuel can never go negative
Goal: Count all possible routes from
This is a classic dynamic programming problem that tests your ability to handle state transitions with constraints!
Imagine you're planning a road trip across several cities with limited fuel! ๐โฝ
You're given an array
locations where locations[i] represents the position of city i on a straight highway. You start at city start with fuel units of gas and want to reach city finish.Travel Rules:
โข You can move from any city
i to any other city j (except the same city)โข Moving from city
i to city j costs |locations[i] - locations[j]| fuelโข You can revisit cities multiple times (including start and finish)
โข Your fuel can never go negative
Goal: Count all possible routes from
start to finish with your available fuel. Since the answer can be huge, return it modulo 109 + 7.This is a classic dynamic programming problem that tests your ability to handle state transitions with constraints!
Input & Output
example_1.py โ Basic Route Counting
$
Input:
locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
โบ
Output:
4
๐ก Note:
There are 4 possible routes: 1โ3 (direct), 1โ0โ3, 1โ2โ3, and 1โ4โ3. Each uses โค5 fuel units.
example_2.py โ Limited Fuel
$
Input:
locations = [4,3,1], start = 1, finish = 0, fuel = 6
โบ
Output:
5
๐ก Note:
Routes: 1โ0, 1โ2โ0, 1โ0โ2โ0, 1โ2โ1โ0, 1โ0โ1โ0. All fit within 6 fuel units.
example_3.py โ No Valid Routes
$
Input:
locations = [5,2,1], start = 0, finish = 2, fuel = 3
โบ
Output:
0
๐ก Note:
Cannot reach city 2 from city 0 with only 3 fuel (minimum distance is 4).
Constraints
- 2 โค locations.length โค 100
- 1 โค locations[i] โค 109
- All locations[i] are distinct
- 0 โค start, finish < locations.length
- 1 โค fuel โค 200
Visualization
Tap to expand
Understanding the Visualization
1
State Definition
Each (city, remaining_fuel) represents a unique state
2
Transition
From each state, try moving to all other cities if fuel allows
3
Base Case
If current city equals finish, count this as one valid route
4
Memoization
Cache results to avoid recalculating the same state
Key Takeaway
๐ฏ Key Insight: Memoization transforms exponential route exploration into polynomial-time computation by caching results for each (city, fuel) state.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code