【LeetCode 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.

思路

要求的是最少公交数量。所以,每到达一个站点,即能到达经过该站点所有公交路线的站点。BFS。

代码

class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
        if (S == T) return 0;
        int n = routes.size();
        map<int, vector<int>> stop2routes;
        
        for (int i=0; i<n; ++i) {
            for (const auto& stop: routes[i]) {
                stop2routes[stop].push_back(i);
            }
        }
        
        map<int, int> visRoute;
        map<int, int> visStop;
        
        queue<int> que;
        que.push(S);
        
        int step = 0;
        
        while(!que.empty()) {
            step++;
            int size = que.size();
            while (size--) {
                int curstop = que.front();
                que.pop();
                for (const auto& route: stop2routes[curstop]) {
                    if (visRoute[route]) continue;
                    visRoute[route]++;
                    for (const auto& nxtstop: routes[route]) {
                        if (visStop[nxtstop]) continue;
                        if (nxtstop == T) return step;
                        visStop[nxtstop]++;
                        que.push(nxtstop);
                    }
                }
            }
        }
        
        return -1;
    }
};

============================================================================
第二次做。。QAQ

发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104894196