LeetCode - 815 公交路线 BFS 广度优先搜索

500个线路,10**6个车站,求s站到t站最少坐几条线

这道题分类很明显 BFS:无向无权图,最短路径

# 难点在于,数据规模较大,怎么处理临接表,怎么优化

两个思路:1 传统的,把车站作为图的节点;2 因为线路的数量少,可以把线路作为图的节点。

优化方面:访问过的车站,访问过的线路,都及时跳过,防止重复遍历

以车站为节点:

import queue
import collections

class StationInfo(object):
    def __init__(self):
        self.Steps = -1
        self.Routes = list()


class Solution(object):


    def numBusesToDestination0(self, routes, source, target):
        """
        :type routes: List[List[int]]
        :type source: int
        :type target: int
        :rtype: int
        """
        if source == target :
            return 0

        bfsq = queue.SimpleQueue()
        stations = collections.defaultdict(StationInfo) #[StationInfo for i in range(10**6)]
        route_visited = [0] * len(routes)
        for rid, r in enumerate(routes):
            for sta in r:
                stations[sta].Routes.append(rid)

        stations[source].Steps = 0
        bfsq.put(source)

        while(not bfsq.empty()):
            a = bfsq.get()
            a_step = stations[a].Steps

            for rid in stations[a].Routes:
                if (route_visited[rid]): continue
                route_visited[rid] = True
                for b in routes[rid]:
                    if (b == target):
                        return a_step + 1

                    b_info = stations[b]
                    if(b_info.Steps >= 0): continue
                    b_info.Steps = a_step + 1
                    bfsq.put(b)

        return -1

以路线为节点:

import queue
import collections

class Solution(object):
    def numBusesToDestination(self, routes, source, target):
        """
        :type routes: List[List[int]]
        :type source: int
        :type target: int
        :rtype: int
        """
        if source == target :
            return 0
        
        s_routes, t_routes = set(), set()
        route_step = [-1 for _ in range(len(routes))]

        for rid, r in enumerate(routes):
            if source in r:
                s_routes.add(rid)
                route_step[rid] = 1
            if target in r:
                t_routes.add(rid)
            routes[rid] = set(r)

        if s_routes & t_routes: ## 如果有共同的路线连接
            return 1

        q = collections.deque(list(s_routes))

        while q:
            r1 = q.popleft()
            r1_step = route_step[r1]

            r2_step = r1_step + 1

            for rid, r in enumerate(routes):
                if (route_step[rid] < 0 and routes[r1] & r): ## 未访问过,且两条路线有相同站点
                    r2 = rid

                    if (r2 in t_routes):
                        return r2_step

                    route_step[r2] = r2_step
                    q.append(r2)

        return -1

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值