1. 程式人生 > 其它 >食堂點餐-微信小程式

食堂點餐-微信小程式

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 <= 105
  • routes[i] 中的所有值 互不相同
  • sum(routes[i].length) <= 105
  • 0 <= routes[i][j] < 106
  • 0 <= source, target < 106
 1 #include <iostream>
 2
#include <unordered_map> 3 #include <vector> 4 #include <queue> 5 using namespace std; 6 7 class Solution { 8 public: 9 int numBusesToDestination(vector<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<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 }