Tutorialspoint
Problem
Solution
Submissions

Bus Routes

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to solve the Bus Routes problem. You are given an array `routes` where `routes[i]` is an array of bus stops on the i-th bus route. You start at the bus stop `source` and want to go to the bus stop `target`. Return the least number of buses you must take to travel from `source` to `target`. Return -1 if it is not possible to reach the destination.

Example 1
  • Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
  • Output: 2
  • Explanation:
    • Start at bus stop 1.
    • Take the first bus route to bus stop 7.
    • Take the second bus route to bus stop 6.
    • This requires a minimum of 2 buses.
Example 2
  • Input: routes = [[7,12,15],[4,5,7],[6,15,19],[2,3,19]], source = 15, target = 12
  • Output: -1
  • Explanation:
    • You cannot reach bus stop 12 from bus stop 15 with the given routes.
    • Bus stop 15 is on routes 0 and 2, but neither of these routes contains bus stop 12.
Constraints
  • 1 ≤ routes.length ≤ 500
  • 1 ≤ routes[i].length ≤ 100
  • All values in routes[i] are unique
  • 0 ≤ routes[i][j] < 10^6
  • 0 ≤ source, target < 10^6
  • Time Complexity: O(N * M) where N is number of routes and M is maximum number of stops in a route
  • Space Complexity: O(N + S) where S is the total number of stops
GraphAlgorithmsCapgeminiPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a graph that maps each bus stop to all bus routes that include this stop
  • Use BFS to find the shortest path from source to target
  • Keep track of visited routes to avoid cycles
  • Count the number of different buses needed
  • Return -1 if target cannot be reached

Steps to solve by this approach:

 Step 1: Check if source and target are the same - if so, return 0.
 Step 2: Create a mapping from each bus stop to all the routes that include it.
 Step 3: Use BFS to find the shortest path, starting from the source stop.
 Step 4: For each stop, explore all connected routes that haven't been visited yet.
 Step 5: For each route, explore all stops that haven't been visited yet.
 Step 6: If target is found, return the number of buses taken plus 1.
 Step 7: If the queue becomes empty without finding the target, return -1.

Submitted Code :