Leetcode 815. Bus Routes

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Bus Routes

2. Solution

**解析:**Version 1,从起始站出发,每一次乘车,按照广度优先进行搜索所有可能到达的车站,将所有可能的车站作为候选的下一次乘车的出发站,重新进行搜索,每一次搜索过的公交车路线要从总路线中剔除,直至没有候选的乘车站为止,由于搜索了很多不能换乘的无用车站,因此超时。Version 2,在Version 1的基础上进行改进,首先遍历所有路线,只保留可以换乘的车站、起始站和终点站,然后再执行Version 1的广度优先搜索,搜索时间大幅缩短,可以超过99%的方法。

  • Version 1
class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        candidates = set([source])
        count = 0
        while candidates:
            if target in candidates:
                return count
            count += 1
            temp = set()
            for cand in candidates:
                indices = []
                for index, route in enumerate(routes):
                    if cand in route:
                        temp |= set(route)
                        indices.append(index)

                for i in indices[::-1]:
                    routes.pop(i)

            candidates = temp
        return -1
  • Version 2
class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        # stat = {}
        # for route in routes:
        #     for stop in route:
        #         stat[stop] = stat.get(stop, 0) + 1

        stat = collections.Counter([x for route in routes for x in route])

        transfers = []
        for route in routes:
            temp = []
            for stop in route:
                if stat[stop] > 1 or stop == source or stop == target:
                    temp.append(stop)
            if len(temp) > 0:
                transfers.append(temp)

        candidates = set([source])
        count = 0
        while candidates:
            if target in candidates:
                return count
            count += 1
            temp = set()
            for cand in candidates:
                indices = []
                for index, route in enumerate(transfers):
                    if cand in route:
                        temp |= set(route)
                        indices.append(index)

                for i in indices[::-1]:
                    transfers.pop(i)

            candidates = temp
        return -1

Reference

  1. https://leetcode.com/problems/bus-routes/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值