Shortest path between two cities without running out of fuel
Last Updated : 23 Jul, 2025
Given a country with N cities connected by M bi-directional roads given in the form of 2D array roads[][], where P cities have fuel stations and (N - P) cities do not. The task is to compute the shortest path from City A to City B, such that a car with maximum fuel capacity of "capacity" can travel without running out of fuel.
Note: 1 unit of fuel is used to travel through any road.
Examples:
Input: N = 7, M = 6, roads = [[1, 2], [2, 3], [3, 4], [4, 5], [4, 6], [6, 7]], A = 1, B = 7, capacity = 4, P = 1, fuel stations = [5]
Output: 7 Explanation: As the shortest path is 1-2-3-4-5-4-6-7
Input: N = 7, M = 6, roads = [[1, 2], [2, 3], [3, 4], [4, 5], [4, 6], [6, 7]], A = 1, B = 7, capacity = 4, P = 2, fuel stations = [5,6] Output: 5 Explanation: As the shortest path is 1-2-3-4-6-7
Approach: To solve the problem, follow the below idea:
We can solve the problem using Breadth First Search. Start a BFS from source node by pushing the current node along with the remaining fuel in the queue. If at any node, the fuel goes to 0, we eliminate that path i.e. we don't add that node's neighbors in the queue again. At the end return the path which takes you to destination while maintaining the fuel capacity.
Step-by-step algorithm:
Build Adjacency List: Create an empty list (adj) for the adjacency list. Iterate over bi-directional roads and add edges to the adjacency list.
Initialize Capacity Array: Create an array (caps) to represent fuel capacity at each city. Mark cities with fuel stations by setting caps[city] = capacity.
Initialize Fuel Array: Create an array (fuel) to represent the current fuel level at each city. Mark the starting city with the full fuel capacity.
Initialize Queue for BFS: Create a deque (que) and add the starting city with distance 0.
Apply BFS: Use a while loop to iterate until the queue is empty. Pop a pair (distance, node) from the queue. If the current node is the destination, return the distance. Iterate over neighbors of the current node, updating their fuel levels under certain conditions. If the condition is true, update the fuel level and enqueue the neighbor with an incremented distance.
Return -1 if Path Not Found: If the loop completes without reaching the destination, return -1, indicating no path.
Below is the implementation of the algorithm:
Output
7
Time Complexity: O(N + M) where N is the number of cities and M is the number of roads. Auxiliary Space: O(N)