[LeetCode]Bus Routes

题目描述:

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,以及公交车站S和T。

求从S到达T最少需要乘坐多少辆车。

解题思路:

广度优先搜索(BFS)

根据车站对公交车进行分组,记为stopBuses

构造字典busNexts,记录每一个公交车的相邻公交车

初始将stopBuses[S]的所有公交车加入队列,执行BFS即可。

Python代码:

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        """
        :type routes: List[List[int]]
        :type S: int
        :type T: int
        :rtype: int
        """
        busNexts = collections.defaultdict(set)
        stopBuses = collections.defaultdict(set)
        for bus, stops in enumerate(routes):
            for stop in stops:
                stopBuses[stop].add(bus)
        for buses in stopBuses.values():
            for bus in buses:
                busNexts[bus] |= set(buses)

        q = stopBuses[S]
        vset = set(q)
        ans = 0
        found = False
        while q and not found:
            q0 = []
            for s in q:
                if s in stopBuses[T]:
                    found = True
                    break
                for n in busNexts[s]:
                    if n not in vset:
                        q0.append(n)
                        vset.add(n)
            q = q0
            ans += 1
        return 0 if S == T else ans if found else -1

 

本文链接:http://bookshadow.com/weblog/2018/04/10/leetcode-bus-routes/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论