Leetcode 815. 公交路线
题目
我们有一系列公交路线。每一条路线 routes[i] 上都有一辆公交车在上面循环行驶。例如,有一条路线 routes[0] = [1, 5, 7],表示第一辆 (下标为0) 公交车会一直按照 1->5->7->1->5->7->1->… 的车站路线行驶。
假设我们从 S 车站开始(初始时不在公交车上),要去往 T 站。 期间仅可乘坐公交车,求出最少乘坐的公交车数量。返回 -1 表示不可能到达终点车站。
示例:
输入:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
输出:2
解释:
最优策略是先乘坐第一辆公交车到达车站 7, 然后换乘第二辆公交车到车站 6。
提示:
- 1 <= routes.length <= 500.
- 1 <= routes[i].length <= 10^5.
- 0 <=routes[i][j] < 10 ^ 6.
题解
建图,将可以由一辆公交车到达的车站连接起来。使用优先队列遍历路线,优先队列为按照乘坐公交车数目的小顶堆。详细过程见代码
代码
class Rote{ //路线
public:
int place; //当前所在地
int carNum; //乘坐的公交车数量
int nowID; //当前称作的公交车id
Rote(int place,int carNum,int nowID){
this->place = place;
this->carNum = carNum;
this->nowID = nowID;
}
bool operator < (const Rote c) const{
return carNum > c.carNum;
}
};
class Car{ //公交车
public:
int id; //编号
int place; //到达地
Car(int id,int place){
this->id = id;
this->place = place;
}
};
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
if(S == T) return 0;
unordered_map<int,vector<Car>> rote;
int n = routes.size();
unordered_map<int,int> appear;
for(int i=0; i<n; i++){ //建立图,只有可以由一辆公交车达到的地方,我们就连接起来
appear.clear();
for(int j=0; j<routes[i].size(); j++){
if(appear[routes[i][j]] == 0){
rote[routes[i][j]].push_back(Car(i,routes[i][(j+1)%routes[i].size()]));
appear[routes[i][j]] = 1;
}
}
}
unordered_map<int,unordered_set<int>> visitPlace;
priority_queue<Rote> q;
for(int i=0; i<rote[S].size(); i++){
q.push(Rote(S,1,rote[S][i].id));
}
while(!q.empty()){
Rote now = q.top();
if(now.place == T) return now.carNum;
visitPlace[now.place].insert(now.nowID); //到达当前地点的最少公交车数可以知道了
q.pop();
for(int i=0; i<rote[now.place].size(); i++){
if(visitPlace[rote[now.place][i].place].count(rote[now.place][i].id) == 0){ //达到该地点的乘坐最少公交车数还未知
if(now.nowID != rote[now.place][i].id) //需要换乘
q.push(Rote(rote[now.place][i].place,now.carNum+1,rote[now.place][i].id));
else //不需要换乘
q.push(Rote(rote[now.place][i].place,now.carNum,now.nowID));
}
}
}
return -1;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bus-routes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。