Saturday, June 1, 2019

LeetCode [815] Bus Routes

815. Bus Routes
Hard

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.

 

Constraints:

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 10^5.
  • 0 <= routes[i][j] < 10 ^ 6.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
        if(S==T) return 0;
        set<int> visitedBus, visitedStops;
        int ret = 0;
        map<int, vector<int>> mp;//stop, bus
        for(int i=0; i<routes.size(); ++i)
        {
            for(auto st:routes[i]){
                mp[st].push_back(i);
            }
        }

        queue<int> que;//stops
        que.push(S);
        queue<int> tmp;
        while(!que.empty())
        {
            int curStop = que.front();
            que.pop();
            for(auto b:mp[curStop]){
                if(visitedBus.count(b)) continue;
                visitedBus.insert(b);
                for(auto s:routes[b]){
                    if(visitedStops.count(s)) continue;
                    if(s==T) return ret+1;
                    visitedStops.insert(s);
                    tmp.push(s);
                }
            }
            if(que.empty()){
                ret++;
                que = tmp;
                queue<int> empty;
                swap(tmp, empty);
            }
        }

        return -1;
    }
};

No comments:

Post a Comment