일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- 월간
- 잡생각
- 10분
- 매일
- 리얼 클래스
- 화상영어
- 3줄정리
- 영어원서읽기
- 만화도
- realclass
- 스탭퍼
- leetcode
- Writing
- 쓰릴오브파이트
- 괜찮음
- 사이드
- 30분
- Daily Challenge
- 링피트
- 운동
- 뭐든
- 읽기
- 개발자
- Problem Solving
- 미드시청
- 영어공부
- FIT XR
- English
- 프로젝트
- 파비최
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.01.26 Today's Challenge 본문
https://leetcode.com/problems/cheapest-flights-within-k-stops/
Cheapest Flights Within K Stops - LeetCode
Cheapest Flights Within K Stops - There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also giv
leetcode.com
priority queue (우선 순위 큐)를 활용하면 DFS 를 쓰는 것보다 좀 더 간단히 풀 수 있음.
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
graph = [[] for _ in range(n)]
min_heap = [(0, src, k+1)]
dist = [[math.inf] * (k+2) for _ in range(n)]
for u, v, w in flights:
graph[u].append((v, w))
while min_heap:
d, u, stops = heapq.heappop(min_heap)
if u == dst:
return d
if stops > 0:
for v, w in graph[u]:
new_dist = d + w
if new_dist < dist[v][stops - 1]:
dist[v][stops - 1] = new_dist
heapq.heappush(min_heap, (new_dist, v, stops - 1))
return -1
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.01.28 Today's Challenge (0) | 2023.01.28 |
---|---|
2023.01.27 Today's Challenge (0) | 2023.01.27 |
2023.01.25 Today's Challenge (0) | 2023.01.25 |
2023.01.24 Today's Challenge (0) | 2023.01.24 |
2023.01.23 Today's Challenge (0) | 2023.01.23 |
Comments