公交路线"/>
Leetcode815之公交路线
题目:
给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。
例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... 这样的车站路线行驶。
现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。
求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1 。
示例 1:
输入:routes = [[1,2,7],[3,6,7]], source = 1, target = 6
输出:2
解释:最优策略是先乘坐第一辆公交车到达车站 7 , 然后换乘第二辆公交车到车站 6 。
示例 2:
输入:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
输出:-1
提示:
1 <= routes.length <= 500.
1 <= routes[i].length <= 105
routes[i] 中的所有值 互不相同
sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
代码:
方法一——使用队列:
class Solution {
public:int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {if (source ==target) {return 0;}unordered_map<int, vector<int>> stop2bus;for (int i = 0; i < routes.size(); i++) {for (const auto& stop : routes[i]) {stop2bus[stop].push_back(i);}}queue<int> q{{source}};int level = 0;unordered_set<int> visited;while (!q.empty()) {for (int k = q.size(); k > 0; k--) {auto curStop = q.front(); q.pop();if (curStop == target) {return level;}for (const auto& bus : stop2bus[curStop]) {if (visited.count(bus)) {continue;}visited.insert(bus);for (const auto& stop : routes[bus]) {q.push(stop);}}}level++;}return -1;}
};
想法:使用一个unorder_map记录每一站会停留的公交车。使用visited集合记录访问过的公交车站,使用队列的方法,从source开始进行宽度优先遍历,如果遍历到的等于target,那么返回level,否则,记录和他同站的没有访问过的车,push每个stop;如果最后的最后没有返回任何level,那么返回-1。
这是一种宽度优先遍历方法。
方法二——也是bfs,仅仅是判断位置有差别:
class Solution {
public:int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {if(source==target)return 0;int level=0;unordered_map<int,vector<int>> stop2bus;queue<int> q{{source}};unordered_set<int> visited;for(int bus=0;bus<routes.size();++bus){for(int stop:routes[bus]){stop2bus[stop].push_back(bus);}}while(!q.empty()){++level;for(int i=q.size();i>0;i--){int t=q.front();q.pop();for(int bus:stop2bus[t]){if(visited.count(bus))continue;visited.insert(bus);for(int stop:routes[bus]){if(stop==target)return level;q.push(stop);}}}}return -1;}
};
更多推荐
Leetcode815之公交路线
发布评论