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

解题思路:对于至少有两条公交线路经过的站点,称为换乘站。如果起点和终点不属于同一公交线路,那么必定要经过换乘站换乘另外的线路。所以对于所有的站点来说,有效的站点只有起点、终点、换乘站。过滤无效站点可以减少计算量,使用BFS即可求得结果。

代码如下:

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        """
        :type routes: List[List[int]]
        :type S: int
        :type T: int
        :rtype: int
        """
        transfer = {}
        for route in routes:
            for r in route:
                transfer[r] = transfer.setdefault(r,0) + 1
        key_list = []
        for key in transfer.viewkeys():
            key_list.append(key)

        for key in key_list:
            if transfer[key] <= 1:del transfer[key]

        for i in range(len(routes)-1,-1,-1):
            for j in range(len(routes[i])-1,-1,-1):
                v = routes[i][j]
                if v != S and v != T and v not in transfer:
                    del routes[i][j]

        #print routes

        visit = {}
        visit[S] = 0
        queue = [(S,0)]
        while len(queue) > 0:
            stop,count = queue.pop(0)
            if stop == T:return count
            for route in routes:
                if stop not in route:
                    continue
                for r in route:
                    if r not in visit or visit[r] > count+1:
                        queue.append((r,count+1))
                        visit[r] = count+1
        return -1

 

posted @ 2019-11-28 10:40  seyjs  阅读(171)  评论(0编辑  收藏  举报