{x}
blog image

Bus Routes

You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.

  • For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.

You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.

Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

 

Example 1:

Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
Output: 2
Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

Example 2:

Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
Output: -1

 

 

Constraints:

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 105
  • All the values of routes[i] are unique.
  • sum(routes[i].length) <= 105
  • 0 <= routes[i][j] < 106
  • 0 <= source, target < 106

Solution Explanation: Breadth-First Search (BFS)

This problem can be efficiently solved using Breadth-First Search (BFS). The goal is to find the shortest path (minimum number of buses) from the source bus stop to the target bus stop. We represent the bus routes as a graph where bus stops are nodes and edges connect stops that are served by the same bus.

Algorithm:

  1. Initialization:

    • Create a dictionary/map (g) to store the adjacency list of the graph. The keys are bus stops, and the values are lists of bus route indices that serve that stop.
    • Create a queue (q) for BFS, initially containing the source stop and a bus count of 0.
    • Create sets (visBus and visStop) to keep track of visited bus routes and visited bus stops, respectively. This prevents cycles and ensures we find the shortest path.
  2. BFS Traversal:

    • While the queue is not empty:
      • Dequeue the current stop and busCount.
      • If the current stop is the target, return busCount.
      • Iterate through the bus routes (buses) that serve the current stop (obtained from g).
      • For each bus route:
        • If the bus route hasn't been visited (visBus):
          • Mark the bus route as visited (visBus).
          • Iterate through all the stops (nextStop) on that bus route.
          • For each nextStop:
            • If the nextStop hasn't been visited (visStop):
              • Mark the nextStop as visited (visStop).
              • Enqueue the nextStop and the incremented busCount (busCount + 1) into the queue.
  3. No Path:

    • If the queue becomes empty without finding the target, it means there's no path, so return -1.

Time and Space Complexity:

  • Time Complexity: O(R * S), where R is the total number of bus routes and S is the total number of stops across all routes. In the worst case, we might visit all stops and routes.
  • Space Complexity: O(R + S), primarily due to the adjacency list (g), visited sets (visBus, visStop), and the queue (q). The size of these data structures is proportional to the number of routes and stops.

Code Examples (Python):

from collections import defaultdict
from collections import deque
 
def numBusesToDestination(routes, source, target):
    if source == target:
        return 0
 
    g = defaultdict(list)  # Adjacency list: stop -> [bus routes]
    for i, route in enumerate(routes):
        for stop in route:
            g[stop].append(i)
 
    if source not in g or target not in g: # Check if source or target is reachable
        return -1
 
    q = deque([(source, 0)])  # (stop, busCount)
    visBus = set()
    visStop = {source}
 
    while q:
        stop, busCount = q.popleft()
        if stop == target:
            return busCount
 
        for bus in g[stop]:
            if bus not in visBus:
                visBus.add(bus)
                for nextStop in routes[bus]:
                    if nextStop not in visStop:
                        visStop.add(nextStop)
                        q.append((nextStop, busCount + 1))
 
    return -1

The code examples in other languages (Java, C++, Go, TypeScript, C#) provided earlier follow the same algorithmic approach, differing only in syntax and data structure implementations. They all maintain the same time and space complexity.