python3 bfs

公交车

http://www.nowcoder.com/questionTerminal/630816b6884f4ad49590b6c07bab40fc

import sys
n,m=map(int,input().split())
route=[]
for line in sys.stdin:
    route.append(list(map(int,line.split()))[1:])
def bus(route,n):
    if n==1:
        return 0
    station={}
    for i,routes in enumerate(route):
        for station_id in routes:
            if station_id in station:
                station[station_id].append(i)
            else:
                station[station_id]=[i]
    source_route=station[1]
    target_route=set(station[n])
    res=1
    used_station,used_route=set(),set()
    for route_id in source_route:
        if route_id in target_route:
            return res
        used_route.add(route_id)
    while source_route:
        res+=1
        next_route=[]
        for route_id in source_route:
            for station_id in route[route_id]:
                if station_id not in used_station:
                    for next_route_id in station[station_id]:
                        if next_route_id not in used_route:
                            if next_route_id in target_route:
                                return res
                            next_route.append(next_route_id)
                            used_route.add(next_route_id)
                used_station.add(station_id)
        source_route=next_route
    return -1
print(bus(route,n))
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务