815. Bus Routes

参考https://blog.youkuaiyun.com/zjucor/article/details/79850104

在他代码基础上,添加了一些个人的理解

from collections import defaultdict  
class Solution:  
    def numBusesToDestination(self, routes, S, T):  
        """ 
        :type routes: List[List[int]] 
        :type S: int 
        :type T: int 
        :rtype: int 
        """  
        if S==T: return 0  
        d = defaultdict(set)  
        for i,l in enumerate(routes):  
            for t in l: 
                d[t].add(i)         #记录每个车站通过的路线集合
          
        res = 1  
#        step = {}  
        vis = set()  
        q,qq=[],[]  
        for t in d[S]:   
            vis.add(t)          #所有通过起点站的路线
            q.append(t)         #所有通过起点站的路线
        while q:  
            while q:  
                g = q.pop()     #挑选一个路线
                for t in routes[g]:     #挑选一个路线上的站点
                    if t==T:            #如果找到终点站,退出
                        return res  
                    for tg in d[t]:     #否则,寻找这个中转站的站点
                        if tg not in vis:   #如果该站没有被访问过
                            vis.add(tg)     #标记访问
                            qq.append(tg)   #记录这些站的集合
            q,qq=qq,q  
            res+=1  
          
        return -1  
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值