815. Bus Routes

问题描述:

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.

 

解题思路:

此时我们有了车到站的对应,我们可以建立一个站到车的对应。

用hash表来辅助我们建立:unordered_map<int, vector<int>> m;

这时候我们其实可以将这些路线的叠加看成一个图。

我们从起点开始bfs遍历:将起点压入队列中,进行层序遍历。

由于我们要求的事最少的换车数,这代表我们同一辆车只经过一次,同一个站点也只经过一次,可以用集合来存储VisitedStops以及VisitedBus。

我们可以用队列的大小size来帮助我们进行层序遍历。

 

代码:

class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
        unordered_map<int, vector<int>> m;
        for(int i = 0 ; i < routes.size(); i++){
            for(int n : routes[i]) m[n].push_back(i);
        }
        
        int ret = 0;
        queue<int> q;
        q.push(S);
        
        unordered_set<int> visitedStops;
        unordered_set<int> visitedBus;
        
        while(!q.empty()){
            int n = q.size();
            unordered_set<int> tmp;
            for(int i = 0; i < n; i++){
                int cur = q.front();
                q.pop();
                if(cur == T) return ret;
                if(visitedStops.count(cur)) continue;
                visitedStops.insert(cur);
                for(auto bus : m[cur]){
                    if(visitedBus.count(bus)) continue;
                    visitedBus.insert(bus);
                    for(auto stop : routes[bus])
                        tmp.insert(stop);
                }
            }
            for(auto s : tmp) q.push(s);
            ret++;
            
        }
        return -1;
    }
};

 

posted @ 2018-08-24 06:14  妖域大都督  阅读(316)  评论(0编辑  收藏  举报