일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- realclass
- 영어공부
- 개발자
- 운동
- 잡생각
- 뭐든
- 파비최
- 스탭퍼
- Daily Challenge
- 괜찮음
- 링피트
- 30분
- Writing
- 3줄정리
- 10분
- 월간
- 리얼 클래스
- FIT XR
- Problem Solving
- 만화도
- leetcode
- English
- 프로젝트
- 사이드
- 화상영어
- 영어원서읽기
- 미드시청
- 매일
- 읽기
- 쓰릴오브파이트
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.11.12 Today's Challenge 본문
https://leetcode.com/problems/bus-routes/
Bus Routes - LeetCode
Can you solve this real interview question? Bus Routes - You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever. * For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in
leetcode.com
이번에도 BFS로 푸는 문제
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
max_stop = max(max(route) for route in routes)
if max_stop < target:
return -1
n = len(routes)
min_buses_to_reach = [float('inf')] * (max_stop + 1)
min_buses_to_reach[source] = 0
flag = True
while flag:
flag = False
for route in routes:
m = float('inf')
for stop in route:
m = min(m, min_buses_to_reach[stop])
m += 1
for stop in route:
if min_buses_to_reach[stop] > m:
min_buses_to_reach[stop] = m
flag = True
return min_buses_to_reach[target] if min_buses_to_reach[target] < float('inf') else -1
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.11.14 Today's Challenge (0) | 2023.11.14 |
---|---|
2023.11.13 Today's Challenge (0) | 2023.11.13 |
2023.11.11 Today's Challenge (1) | 2023.11.11 |
2023.11.10 Today's Challenge (0) | 2023.11.10 |
2023.11.09 Today's Challenge (0) | 2023.11.09 |
Comments