参考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