A variant of Dijkstra's shortest path algorithm that models a vehicle driving between cities with fuel constraints and gas stations.
Given:
Ncities andMroads forming a weighted graph- A fuel tank with maximum capacity
L - A subset of cities marked as gas stations (refuel to full when visited)
Compute how many cities are reachable from city #1 without ever running out of fuel.
Modified Dijkstra using a min-heap:
- Initialize all distances to ∞, except the source = 0
- Pop the city with the lowest fuel-used so far
- If the city is a gas station → reset fuel-used to 0
- For each neighbor, push if
(current_fuel_used + edge_weight) ≤ L - Count how many cities have a final distance ≤ L
.
└── dijkstra_algorithm/
├── algorithm.py # Main solver (input from stdin)
└── input.txt # Sample input
N M L # cities, roads, fuel capacity
0101... # gas-station bitmap (length N)
u v d # M lines: edge between u and v with weight d
...
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activateNo external dependencies (uses only heapq and sys from stdlib).
python dijkstra_algorithm/algorithm.py < dijkstra_algorithm/input.txt- Time: O((N + M) log N)
- Space: O(N + M)
MIT