|
| 1 | +# 815. Bus Routes |
| 2 | + |
| 3 | +**<font color=red>难度: Hard</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | +
|
| 9 | +* https://leetcode.com/problems/bus-routes/description/ |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | +
|
| 13 | +``` |
| 14 | +
|
| 15 | +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. |
| 16 | +
|
| 17 | +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. |
| 18 | +
|
| 19 | +Example: |
| 20 | +Input: |
| 21 | +routes = [[1, 2, 7], [3, 6, 7]] |
| 22 | +S = 1 |
| 23 | +T = 6 |
| 24 | +Output: 2 |
| 25 | +Explanation: |
| 26 | +The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. |
| 27 | +Note: |
| 28 | +
|
| 29 | +1 <= routes.length <= 500. |
| 30 | +1 <= routes[i].length <= 500. |
| 31 | +0 <= routes[i][j] < 10 ^ 6. |
| 32 | +```` |
| 33 | +
|
| 34 | +## 解题方案 |
| 35 | +
|
| 36 | +> 思路 1 |
| 37 | +******- 时间复杂度: O(VE)******- 空间复杂度: O(VE)****** |
| 38 | +
|
| 39 | +看作是一个图的话,V是bus,E是bus所在的routes,那么时间和空间复杂度都是O(VE) |
| 40 | +
|
| 41 | +```python |
| 42 | +class Solution(object): |
| 43 | + def numBusesToDestination(self, routes, S, T): |
| 44 | + """ |
| 45 | + :type routes: List[List[int]] |
| 46 | + :type S: int |
| 47 | + :type T: int |
| 48 | + :rtype: int |
| 49 | + """ |
| 50 | + bus_in_routes, cur_buses, step, visited = collections.defaultdict(set), [S], 0, set() |
| 51 | + for i, route in enumerate(routes): |
| 52 | + for bus in route: |
| 53 | + bus_in_routes[bus].add(i) # this bus is in route i |
| 54 | + while cur_buses: |
| 55 | + new_buses = [] |
| 56 | + for bus in cur_buses: |
| 57 | + if bus == T: |
| 58 | + return step |
| 59 | + for route_idx in bus_in_routes[bus]: |
| 60 | + if route_idx not in visited: |
| 61 | + visited.add(route_idx) |
| 62 | + for new_bus in routes[route_idx]: |
| 63 | + if new_bus != bus: |
| 64 | + new_buses.append(new_bus) |
| 65 | + cur_buses = new_buses |
| 66 | + step += 1 |
| 67 | + return -1 |
| 68 | +``` |
0 commit comments