833. Bus Routes

  • Difficulty: Hard

  • Topics: Breadth-first Search

  • Similar Questions:

Problem:

We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.

We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.

Example:
Input: 
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 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.

Note:

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 500.
  • 0 <= routes[i][j] < 10 ^ 6.

Solutions:

class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
        if (S == T) return 0;
        map<int, vector<int>> stopToRoutes;
        for (int i = 0; i < routes.size(); ++i) {
            for (int j = 0; j < routes[i].size(); ++j) {
                stopToRoutes[routes[i][j]].push_back(i);
            }
        }

        unordered_set<int> visitedStops;
        unordered_set<int> visitedRoutes;
        queue<int> q;
        q.push(S);
        int ret = 0;
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                int stop = q.front(); q.pop();
                if (stop == T)  return ret;
                for (auto& route : stopToRoutes[stop]) {
                    if (visitedRoutes.count(route)) continue;
                    visitedRoutes.insert(route);
                    for (auto& neighbor : routes[route]) {
                        if (visitedStops.count(neighbor))   continue;
                        visitedStops.insert(neighbor);
                        q.push(neighbor);
                    }
                }
            }
            ++ret;
        }

        return -1;

    }
};

results matching ""

    No results matching ""