Powered by:NEFU AB-IN
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
# BFS
dis = {source: 0}
q = deque([source])
while q:
x = q.popleft() # 当前在车站 x
dis_x = dis[x]
for i in stop_to_buses[x]: # 遍历所有经过车站 x 的公交车 i
if routes[i]:
for y in routes[i]: # 遍历公交车 i 的路线
if y not in dis: # 没有访问过车站 y
dis[y] = dis_x + 1 # 从 x 站上车然后在 y 站下车
q.append(y)
routes[i] = None # 标记 routes[i] 遍历过
return dis.get(target, -1)