일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 뭐든
- 영어공부
- 읽기
- 파비최
- Writing
- 만화도
- 괜찮음
- leetcode
- 미드시청
- 개발자
- 30분
- FIT XR
- 화상영어
- English
- 쓰릴오브파이트
- 스탭퍼
- 월간
- 리얼 클래스
- 3줄정리
- 운동
- 10분
- Daily Challenge
- 잡생각
- 매일
- 링피트
- Problem Solving
- 영어원서읽기
- 사이드
- 프로젝트
- realclass
Archives
- Today
- Total
파비의 매일매일 공부기록
2023.11.13 Today's Challenge 본문
Design Graph With Shortest Path Calculator - LeetCode
Can you solve this real interview question? Design Graph With Shortest Path Calculator - There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where e
leetcode.com
다익스트라 알고리즘으로 푸는 문제
class Graph:
def __init__(self, n: int, edges: List[List[int]]):
self.adj_list = [[] for _ in range(n)]
for from_node, to_node, cost in edges:
self.adj_list[from_node].append((to_node, cost))
def addEdge(self, edge: List[int]) -> None:
from_node, to_node, cost = edge
self.adj_list[from_node].append((to_node, cost))
def shortestPath(self, node1: int, node2: int) -> int:
n = len(self.adj_list)
pq = [(0, node1)]
cost_for_node = [inf] * (n)
cost_for_node[node1] = 0
while pq:
curr_cost, curr_node = heappop(pq)
if curr_cost > cost_for_node[curr_node]:
continue
if curr_node == node2:
return curr_cost
for neighbor, cost in self.adj_list[curr_node]:
new_cost = curr_cost + cost
if new_cost < cost_for_node[neighbor]:
cost_for_node[neighbor] = new_cost
heappush(pq, (new_cost, neighbor))
return -1
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
2023.11.15 Today's Challenge (0) | 2023.11.15 |
---|---|
2023.11.14 Today's Challenge (0) | 2023.11.14 |
2023.11.12 Today's Challenge (0) | 2023.11.12 |
2023.11.11 Today's Challenge (1) | 2023.11.11 |
2023.11.10 Today's Challenge (0) | 2023.11.10 |
Comments