1. Stop-Level BFS
Intuition
Model every bus stop as a graph vertex. Connect every pair of stops that belong to the same bus route with an edge. Run BFS from source to target. However, since a route with K stops adds O(K2) edges, dense routes lead to Time and Memory Limit Exceeded.
Algorithm
- If
source == target, return 0. - For each route, connect all pairs of stops (u, v) in an adjacency list.
- Run BFS from
sourcestop. - This incurs quadratic edge explosion (K2) for large routes.
#include <iostream>#include <vector>#include <unordered_map>#include <unordered_set>#include <queue> int numBusesToDestinationBrute(std::vector<std::vector<int>>& routes, int source, int target) { if (source == target) return 0; std::unordered_map<int, std::unordered_set<int>> adj; for (const auto& route : routes) { for (size_t i = 0; i < route.size(); ++i) { for (size_t j = i + 1; j < route.size(); ++j) { adj[route[i]].insert(route[j]); adj[route[j]].insert(route[i]); } } } std::queue<std::pair<int, int>> q; std::unordered_set<int> visited; q.push({source, 0}); visited.insert(source); while (!q.empty()) { auto [stop, buses] = q.front(); q.pop(); if (stop == target) return buses; for (int next : adj[stop]) { if (!visited.count(next)) { visited.insert(next); q.push({next, buses + 1}); } } } return -1;} int main() { std::vector<std::vector<int>> routes = {{1, 2, 7}, {3, 6, 7}}; std::cout << "Buses (Brute): " << numBusesToDestinationBrute(routes, 1, 6) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(sum(K_i^2)) which exceeds time limits when routes have 10^5 stops. - Space complexity:
O(sum(K_i^2)) memory explosion.