일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 30. Substring with Concatenation of All Words
- Python Implementation
- Python Code
- 밴픽
- Generator
- Regular Expression
- iterator
- 파이썬
- Python
- DWG
- Substring with Concatenation of All Words
- 715. Range Module
- Decorator
- 프로그래머스
- 315. Count of Smaller Numbers After Self
- 운영체제
- LeetCode
- attribute
- kaggle
- 컴퓨터의 구조
- 시바견
- t1
- Protocol
- shiba
- Convert Sorted List to Binary Search Tree
- Class
- 43. Multiply Strings
- concurrency
- data science
- 109. Convert Sorted List to Binary Search Tree
Archives
- Today
- Total
Scribbling
LeetCode: 743. Network Delay Time 본문
다익스트라 알고리즘을 활용하여 푼다.
import heapq
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
INF = int(1e9)
graph = [[] for _ in range(n+1)]
distance = [INF] * (n+1)
for time in times:
u = time[0]
v = time[1]
w = time[2]
graph[u].append((w, v))
self.dijkstra(graph, distance, k)
max_dist = 0
for i in range(1, n+1):
max_dist = max(max_dist, distance[i])
if max_dist == INF:
return -1
else:
return max_dist
def dijkstra(self, graph, distance, start):
q = []
distance[start] = 0
heapq.heappush(q, (0, start))
while q:
dist_u, u = heapq.heappop(q)
if distance[u] < dist_u:
continue
for item in graph[u]:
dist_uv = item[0]
v = item[1]
if distance[v] > dist_u + dist_uv:
distance[v] = dist_u + dist_uv
heapq.heappush(q, (distance[v], v))
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 5. Longest Palindromic Substring (0) | 2021.08.12 |
---|---|
LeetCode: 787. Cheapest Flights Within K Stops (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: 2. Add Two Numbers (0) | 2021.08.10 |