当前位置: 首页> 房产> 建筑 > 815. 公交路线

815. 公交路线

时间:2025/7/15 14:57:05来源:https://blog.csdn.net/qq_45859188/article/details/142337843 浏览次数:0次

Powered by:NEFU AB-IN

Link

文章目录

  • 815. 公交路线
    • 题意
    • 思路
    • 代码

815. 公交路线

题意

给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。

例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> … 这样的车站路线行驶。
现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。

求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1 。

思路

记下每个车站由哪些车路过,然后从起点开始bfs,坐车遍历车能到的车站,注意车只遍历一次,车站也是,复杂度为线性

代码

'''
Author: NEFU AB-IN
Date: 2024-09-17 16:19:02
FilePath: \LeetCode\815\815.py
LastEditTime: 2024-09-18 16:43:32
'''
# 3.8.9 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)# Set recursion limit
setrecursionlimit(int(2e9))class Arr:array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])graph = staticmethod(lambda size=N: [[] for _ in range(size)])class Math:max = staticmethod(lambda a, b: a if a > b else b)min = staticmethod(lambda a, b: a if a < b else b)class Std:pass# ————————————————————— Division line ——————————————————————class Solution:def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:# 记录经过车站 x 的公交车编号stop_to_buses = defaultdict(list)for i, route in enumerate(routes):for x in route:stop_to_buses[x].append(i)# 小优化:如果没有公交车经过起点或终点,直接返回if source not in stop_to_buses or target not in stop_to_buses:# 注意原地 TP 的情况return -1 if source != target else 0# BFSdis = {source: 0}q = deque([source])while q:x = q.popleft()  # 当前在车站 xdis_x = dis[x]for i in stop_to_buses[x]:  # 遍历所有经过车站 x 的公交车 iif routes[i]:for y in routes[i]:  # 遍历公交车 i 的路线if y not in dis:  # 没有访问过车站 ydis[y] = dis_x + 1  # 从 x 站上车然后在 y 站下车q.append(y)routes[i] = None  # 标记 routes[i] 遍历过return dis.get(target, -1)
关键字:815. 公交路线

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: