首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Leetcode 815. Bus Routes

Leetcode 815. Bus Routes

作者头像
Tyan
发布2021-07-08 16:26:32
发布2021-07-08 16:26:32
38200
代码可运行
举报
文章被收录于专栏:SnailTyanSnailTyan
运行总次数:0
代码可运行

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript
代码运行次数:0
运行
复制
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
代码语言:javascript
代码运行次数:0
运行
复制
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/
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档