[LeetCode] 815. Bus Routes 公交路线
We have a list of bus routes. Each routes[i]
is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7]
, this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stop S
(initially not on a bus), and we want to go to bus stop T
. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Note:
1 <= routes.length <= 500
.1 <= routes[i].length <= 500
.0 <= routes[i][j] < 10 ^ 6
.
有一个表示公交路线的二维数组,每一行routes[i]代表一辆公交车循环运行的环形路线,求最少需要坐多少辆公交车才能从巴士站S到达T。
解法:BFS,先对原来的二维数组进行处理,二维数组的每一行代表这辆公交车能到达的站点,用HashMap记录某站点有哪个公交经过。这样处理完以后就知道每一个站点都有哪个公交车经过了。然后用一个queue记录当前站点,对于当前站点的所有经过的公交循环,每个公交又有自己的下一个站点。可以想象成一个图,每一个公交站点 被多少个公交经过,也就是意味着是个中转站,可以连通到另外一个公交上, 因为题目求的是经过公交的数量而不关心经过公交站点的数量,所以在BFS的时候以公交(也就是routes的下标)来扩展。
Java:
class Solution {
public int numBusesToDestination(int[][] routes, int S, int T) {
HashSet<Integer> visited = new HashSet<>();
Queue<Integer> q = new LinkedList<>();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
int ret = 0; if (S==T) return 0; for(int i = 0; i < routes.length; i++){
for(int j = 0; j < routes[i].length; j++){
ArrayList<Integer> buses = map.getOrDefault(routes[i][j], new ArrayList<>());
buses.add(i);
map.put(routes[i][j], buses);
}
} q.offer(S);
while (!q.isEmpty()) {
int len = q.size();
ret++;
for (int i = 0; i < len; i++) {
int cur = q.poll();
ArrayList<Integer> buses = map.get(cur);
for (int bus: buses) {
if (visited.contains(bus)) continue;
visited.add(bus);
for (int j = 0; j < routes[bus].length; j++) {
if (routes[bus][j] == T) return ret;
q.offer(routes[bus][j]);
}
}
}
}
return -1;
}
}
Java:
public int numBusesToDestination(int[][] routes, int S, int T) {
HashMap<Integer, HashSet<Integer>> to_routes = new HashMap<>();
for (int i = 0; i < routes.length; ++i)
for (int j : routes[i]) {
if (!to_routes.containsKey(j)) to_routes.put(j, new HashSet<Integer>());
to_routes.get(j).add(i);
}
Queue<Point> bfs = new ArrayDeque();
bfs.offer(new Point(S, 0));
HashSet<Integer> seen = new HashSet<>();
seen.add(S);
while (!bfs.isEmpty()) {
int stop = bfs.peek().x, bus = bfs.peek().y;
bfs.poll();
if (stop == T) return bus;
for (int route_i : to_routes.get(stop))
for (int next_stop : routes[route_i])
if (!seen.contains(next_stop)) {
seen.add(next_stop);
bfs.offer(new Point(next_stop, bus + 1));
}
}
return -1;
}
Python:
def numBusesToDestination(self, routes, S, T):
to_routes = collections.defaultdict(set)
for i,route in enumerate(routes):
for j in route: to_routes[j].add(i)
bfs = [(S,0)]
seen = set([S])
for stop, bus in bfs:
if stop == T: return bus
for route_i in to_routes[stop]:
for next_stop in routes[route_i]:
if next_stop not in seen:
bfs.append((next_stop, bus+1))
seen.add(next_stop)
routes[route_i] = []
return -1
Python:
# Time: O(|V| + |E|)
# Space: O(|V| + |E|) import collections class Solution(object):
def numBusesToDestination(self, routes, S, T):
"""
:type routes: List[List[int]]
:type S: int
:type T: int
:rtype: int
"""
if S == T:
return 0 to_route = collections.defaultdict(set)
for i, route in enumerate(routes):
for stop in route:
to_route[stop].add(i) result = 1
q = [S]
lookup = set([S])
while q:
next_q = []
for stop in q:
for i in to_route[stop]:
for next_stop in routes[i]:
if next_stop in lookup:
continue
if next_stop == T:
return result
next_q.append(next_stop)
to_route[next_stop].remove(i)
lookup.add(next_stop)
q = next_q
result += 1 return -1
C++:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
unordered_map<int, unordered_set<int>> to_route;
for (int i = 0; i < routes.size(); ++i) for (auto& j : routes[i]) to_route[j].insert(i);
queue<pair<int, int>> bfs; bfs.push(make_pair(S, 0));
unordered_set<int> seen = {S};
while (!bfs.empty()) {
int stop = bfs.front().first, bus = bfs.front().second;
bfs.pop();
if (stop == T) return bus;
for (auto& route_i : to_route[stop]) {
for (auto& next_stop : routes[route_i])
if (seen.find(next_stop) == seen.end()) {
seen.insert(next_stop);
bfs.push(make_pair(next_stop, bus + 1));
}
routes[route_i].clear();
}
}
return -1;
}
All LeetCode Questions List 题目汇总
[LeetCode] 815. Bus Routes 公交路线的更多相关文章
- [LeetCode] Bus Routes 公交线路
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For e ...
- 【leetcode】815. Bus Routes
题目如下: We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. ...
- [Swift]LeetCode815. 公交路线 | Bus Routes
We have a list of bus routes. Each routes[i]is a bus route that the i-th bus repeats forever. For ex ...
- Java实现 LeetCode 815 公交路线(创建关系+BFS)
815. 公交路线 我们有一系列公交路线.每一条路线 routes[i] 上都有一辆公交车在上面循环行驶.例如,有一条路线 routes[0] = [1, 5, 7],表示第一辆 (下标为0) 公交车 ...
- UVA 1349 Optimal Bus Route Design 最优公交路线(最小费用流,拆点)
题意: 给若干景点,每个景点有若干单向边到达其他景点,要求规划一下公交路线,使得每个景点有车可达,并且每个景点只能有1车经过1次,公车必须走环形回到出发点(出发点走2次).问是否存在这样的线路?若存在 ...
- LeetCode解题报告—— Bus Routes
We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For e ...
- Android定位&地图&导航——自定义公交路线代码
一.问题描述 基于百度地图实现检索指定城市指定公交的交通路线图,效果如图所示 二.通用组件Application类,主要创建并初始化BMapManager public class App exten ...
- URAL 1137 Bus Routes(欧拉回路路径)
1137. Bus Routes Time limit: 1.0 secondMemory limit: 64 MB Several bus routes were in the city of Fi ...
- android百度地图开发之自动定位所在位置与固定位置进行驾车,步行,公交路线搜索
最近跟着百度地图API学地图开发,先是学了路径搜索,对于已知坐标的两点进行驾车.公交.步行三种路径的搜索(公交路径运行没效果,待学习中),后来又 学了定位功能,能够获取到自己所在位置的经纬度,但当将两 ...
随机推荐
- Kotlin调用Java程序解析
Kotlin跟Java是百分百兼容的,换言之,也就是它们俩是可以互操作的,也就是Java可以调Kotlin,Koltin可以调Java,所以下面来看一下在Kotlin中如何来调用Java代码: 咱们来 ...
- vue $emit、$on、$refs简介
1.$emit 触发当前实例上的事件.附加参数都会传给监听器回调 ex: 子组件调用父组件的方法并传递数据注意:子组件标签中的时间也不区分大小写要用“-”隔开 子组件: <template> ...
- Vue.js not detected
安装vue devtools工具,在chrome中一直是灰色,title是Vue.js not detected ① F12关闭开发者模式 ② 刷新 ③ 然后再按F12就好了 网上看到的,居然真的有用 ...
- stm32flash的读写特性
在使用stm32自带的flash保存数据时候,如下特点必须知道: 1.必须是先擦除一个扇区,才能写入 2.读数据没有限制 3.写数据必须是2字节,同时写入地址以一定要考虑字节对齐, 4.一般都是在最后 ...
- EF实体类指定部分属性不映射数据库标记
命名空间 ;using System.ComponentModel.DataAnnotations.Schema; 实体部分 public partial class Student { [NotMa ...
- JS获取本周、本季度、本月、上月、本年的开始日期、结束日期
/** * 获取本周.本季度.本月.上月的开始日期.结束日期 */ var now = new Date(); //当前日期 var nowDayOfWeek = now.getDay(); //今 ...
- spring boot+Quartz+数据库存储
SpingBoot+Quartz+数据库存储 1.Spring整合Quartz 2.读取数据库中表达式启动定时任务1(每5s执行) 3.更改定时任务状态(启用/禁用),定时任务1停止 4.读取数据库中 ...
- 基金名称中的ABC是什么意思,我们该如何选择?
作者:牛大 | 公众号:定投五分钟 大家好,我是牛大.每天五分钟,投资你自己:坚持基金定投,终会财富自由! 大家经常会看到基金名称后面有字母ABC,这个表示什么意思呢,以及我们该如何选择呢?今天牛大给 ...
- MongoDB 红宝书-MongoDB官网使用指南
本文转载自Mongodb中文社区:http://www.mongoing.com/archives/27359 无论你是MongoDB的使用者.爱好者.初学者还是路人甲,有一个学习与进修的资源宝藏是千 ...
- 关于System.BadImageFormatException
什么是BadImageFormatException BadImageFormatException是当动态链接库 (DLL) 或可执行程序的文件映像无效时引发的异常. 可能的原因 如果动态链接库 ( ...