公交路线
我们有一系列公交路线。每一条路线 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 <= 500.
0 <= routes[i][j] < 10 ^ 6.
分析:我们要求的是最少需要乘坐的公交车数量,我们可以先预处理出公交车之间能互相到达的站台,然后以预处理为基准来进行BFS。即得到结果
class Solution { public: bool check(const vector<int>& A, const vector<int>& B){ int i=0,j=0; while(i<A.size()&&j<B.size()){ if(A[i]==B[j]) return true; else if(A[i]<B[j]) i++; else j++; } return false; } int numBusesToDestination(vector<vector<int>>& routes, int S, int T) { if(S==T)return 0; int n=routes.size(); for(int i=0;i<n;i++) sort(routes[i].begin(),routes[i].end()); vector<vector<int>>graph(n); for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if(check(routes[i],routes[j])){ graph[i].push_back(j); graph[j].push_back(i); } vector<int>dis(n,INT_MAX); queue<int>q; for(int i=0;i<n;i++) for(auto x:routes[i]) if(x==S){ dis[i]=1; q.push(i); break; } while(q.size()){ auto u=q.front(); q.pop(); for(auto x:routes[u]) if(x==T) return dis[u]; for(auto x:graph[u]){ if(dis[x]>dis[u]+1){ dis[x]=dis[u]+1; q.push(x); } } } return -1; } };