815. 公交路线
815. 公交路线
给你一个数组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 <= 105routes[i]中的所有值 互不相同sum(routes[i].length) <= 1050 <= routes[i][j] < 1060 <= source, target < 106
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 7 class Solution { 8 public: 9 int numBusesToDestination(vector int>>& routes, int source, int target) { 10 if (source == target) { 11 return 0; 12 } 13 unordered_map<int, vector<int>> hashMap; // key->公交站点, value->经过该站点的公交线路 14 // 标记访问的线路 15 vector<bool> visited(routes.size(), false); 16 for (unsigned int i = 0; i < routes.size(); i++) { 17 for (unsigned int j = 0; j < routes[i].size(); j++) { 18 // 记录站点出现的线路 19 hashMap[routes[i][j]].push_back(i); 20 } 21 } 22 queue<int> busStationList; 23 // 起始站点入队列 24 busStationList.push(source); 25 int step = 0; // 换乘公交数量 26 while (!busStationList.empty()) { 27 step++; 28 unsigned int len = busStationList.size(); 29 for (unsigned int i = 0; i < len; i++) { 30 int station = busStationList.front(); 31 busStationList.pop(); 32 // 遍历当前处理的站点所在线路 33 for (const auto &r : hashMap[station]) { 34 // 如果当前线路未被访问过 35 if (!visited[r]) { 36 // 遍历当前线路上所有站点,如果当前线路上包含目的站点,则返回换乘车辆数, 37 // 否则将当前线路站点入队列 38 for (unsigned int j = 0; j < routes[r].size(); j++) { 39 if (routes[r][j] == target) { 40 return step; 41 } 42 busStationList.push(routes[r][j]); 43 } 44 visited[r] = true; 45 } 46 } 47 } 48 } 49 // 所有换乘线路均无法到达则返回-1 50 return -1; 51 } 52 }; 53 54 int main() 55 { 56 Solution *test = new Solution(); 57 int source = 1; 58 int target = 6; 59 vector int>> routes = {{1, 2, 7}, {3, 6, 7}}; 60 cout << test->numBusesToDestination(routes, source, target) << endl; // 2 61 system("pause"); 62 return 0; 63 }