일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Regular Expression
- 315. Count of Smaller Numbers After Self
- Python Code
- Python
- 715. Range Module
- shiba
- 운영체제
- DWG
- concurrency
- attribute
- 시바견
- kaggle
- 파이썬
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- Python Implementation
- Decorator
- t1
- iterator
- data science
- LeetCode
- 프로그래머스
- Protocol
- Class
- 컴퓨터의 구조
- 30. Substring with Concatenation of All Words
- Generator
- 43. Multiply Strings
Archives
- Today
- Total
Scribbling
LeetCode: 787. Cheapest Flights Within K Stops 본문
Computer Science/Coding Test
LeetCode: 787. Cheapest Flights Within K Stops
focalpoint 2021. 8. 12. 13:26src로부터 특정 dst까지의 최단 거리를 묻는 문제로, 다익스트라 알고리즘을 먼저 떠올릴 수 있다.
기본적인 형태의 다익스트라 알고리즘은, priority queue에 "최단 거리가 갱신되는 경우"를 추가한다.
하지만 이 문제는 "이동 횟수 제한"이 있으므로, 이를 수정해야한다.
즉, priority queue에 "최단 거리가 갱신되는 경우"를 추가하는 것이 아니라, "추가적으로 이동 가능한 경우"를 모두 추가할 필요가 있다.
이를 코드로 구현하면 아래와 같다.
import heapq
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
INF = int(1e9)
graph = [[] * n for _ in range(n)]
for a, b, c in flights:
graph[a].append((c, b))
dist_list = [INF] * n
dist_list[src] = 0
q = []
# (dist_u, u, num_move)
heapq.heappush(q, (0, src, 0))
while q:
dist_u, u, num_move = heapq.heappop(q)
if u == dst:
return dist_u
if num_move >= k + 1:
continue
for dist_uv, v in graph[u]:
heapq.heappush(q, (dist_u + dist_uv, v, num_move + 1))
return -1
물론 상기 코드를 그대로 제출하면 time limit으로 accept되지 않는다.
이는 priority queue에서 나오는 모든 경우를 다 테스트하기 때문이다.
그러나, 아래와 같은 케이스는 테스트가 불필요함을 알 수 있다.
: 해당 접점까지의 이동 횟수 >= 해당 접점까지 최단거리 경로의 이동 횟수
따라서 상기 조건을 만족하는 경우는 배제해준다.
import heapq
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
INF = int(1e9)
graph = [[] * n for _ in range(n)]
for a, b, c in flights:
graph[a].append((c, b))
dist_list = [INF] * n
num_move_list = [INF] * n
dist_list[src] = 0
q = []
# (dist_u, u, num_move)
heapq.heappush(q, (0, src, 0))
while q:
dist_u, u, num_move = heapq.heappop(q)
if u == dst:
return dist_u
if num_move >= num_move_list[u]:
continue
if num_move >= k + 1:
continue
num_move_list[u] = num_move
for dist_uv, v in graph[u]:
heapq.heappush(q, (dist_u+dist_uv, v, num_move+1))
return -1
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 1584. Min Cost to Connect All Points (0) | 2021.08.13 |
---|---|
LeetCode: 5. Longest Palindromic Substring (0) | 2021.08.12 |
LeetCode: 3. Longest Substring Without Repeating Characters (0) | 2021.08.11 |
LeetCode: 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance (0) | 2021.08.10 |
LeetCode: 743. Network Delay Time (0) | 2021.08.10 |