My first instinct was BFS over stops, which is the wrong layer of abstraction.
Model the problem as a graph where each bus route is a node, and there is an edge between two routes if they share a common stop. Then perform BFS from all routes containing the source stop to find the minimum number of routes (buses) needed to reach any route containing the target stop. If the source and target are the same stop, return 0; if no path exists, return -1.
Pro tip: Clarify that you're counting buses (routes taken), not stops, and handle the edge case where source equals target upfront. Also, mention that precomputing stop-to-routes mapping optimizes the BFS.
Confirm that each bus route is a cycle and you can transfer between routes at shared stops. The goal is to minimize the number of buses taken, i.e., the number of routes used.
Create a mapping from each stop to the list of routes that include it. Also, represent each route as a node, and add edges between routes that share at least one stop.
Initialize a queue with all routes containing the source stop, marking them as visited with distance 1. Perform BFS, exploring neighboring routes (those sharing a stop) and incrementing distance by 1 for each new route.
During BFS, if you encounter a route that contains the target stop, return the current distance. If the queue is exhausted without finding the target, return -1.
If source equals target, return 0 immediately. Also, consider if source or target is not in any route, return -1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.