-
给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。
-
例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> … 这样的车站路线行驶。
现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。 -
求出
最少乘坐的公交车数量
。如果不可能到达终点车站,返回 -1 。
由于求解的目标是最少乘坐的公交车数量,对于同一辆公交车,乘客可以在其路线中的任意车站间无代价地移动,于是我们可以把公交路线当作点。如果两条公交路线有相同车站,则可以在这两条路线间换乘公交车,那么这两条公交路线之间可视作有一条长度为
1 的边。这样建出的图包含的点数即为公交路线的数量,记作 n。
示例 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
通过次数37,769提交次数85,039
题解
- 求最少乘坐的公交车数量,可将每个公交车的线路看成一个点,如果两条公交路线有相同车站,那么这两条公交路线之间可视作有一条长度为 1 的边。
code
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define INT_MAX 0x3f3f3f3f
using namespace std;
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) {
return 0;
}
int n = routes.size();
vector<vector<int>> edge(n, vector<int>(n));
unordered_map<int, vector<int>> mymap;// route[i] ->i
for (int i = 0; i < n; i++) {
for (int site : routes[i]) {
for (int j : mymap[site]) {
edge[i][j] = edge[j][i] = true; // 邻接矩阵
}
mymap[site].push_back(i);
}
}
vector<int> dis(n, -1);
queue<int> que;
for (int bus : mymap[source]) {// mymap[source]为source所在的车站的索引,即从所有能到source的车站开始BFS
dis[bus] = 1;
que.push(bus);
}
while (!que.empty()) {
int x = que.front();
que.pop();
for (int y = 0; y < n; y++) {
if (edge[x][y] && dis[y] == -1) {
dis[y] = dis[x] + 1;
que.push(y);
}
}
}
int ret = INT_MAX;
for (int bus : mymap[target]) {
if (dis[bus] != -1) {
ret = min(ret, dis[bus]);
}
}
return (ret == INT_MAX) ? -1 : ret;
}
};
// https://leetcode.cn/problems/bus-routes/solution/gong-jiao-lu-xian-by-leetcode-solution-yifz/
int main(){
Solution mysolo;
vector< vector<int>> route = {{1,2,7},
{3,6,7}};
int source = 1, target = 6;
int res = mysolo.numBusesToDestination(route,source,target);
cout << "--" <<res << "--";
return 0;
}
- 因为举例全为1,所以DFS和DJ等价。