# 815. Bus Routes

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/bus-routes/description/

> 内容描述

```

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.
````

## 解题方案

![](https://github.com/apachecn/awesome-algorithm/blob/master/images/815/WechatIMG6057.png)

其实还有第三种解法，就是看stop能到哪些stop，但是也是TLE
> 思路 1
******- 时间复杂度: O(VE)******- 空间复杂度: O(VE)******

这里用了截图中的第一种思路

看作是一个图的话，V是bus，E是bus所在的routes，那么时间和空间复杂度都是O(VE)

beats 90.45%

```python
class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        """
        :type routes: List[List[int]]
        :type S: int
        :type T: int
        :rtype: int
        """
        bus_in_routes, cur_buses, step, visited = collections.defaultdict(set), [S], 0, set()
        for i, route in enumerate(routes):
            for bus in route:
                bus_in_routes[bus].add(i) # this bus is in route i
        while cur_buses:
            new_buses = []
            for bus in cur_buses:
                if bus == T:
                    return step
                
                for route_idx in bus_in_routes[bus]:
                    if route_idx not in visited:
                        visited.add(route_idx)
                        for new_bus in routes[route_idx]:
                            if new_bus != bus:
                                new_buses.append(new_bus)
                        routes[route_idx] = [] # this line is optional, more efficient if added
            cur_buses = new_buses
            step += 1
        return -1
```
