# 2642. Design Graph With Shortest Path Calculator ###### tags: `Leetcode` `Hard` `Dijkstra` Link: https://leetcode.com/problems/design-graph-with-shortest-path-calculator/description/ ## Code ```python= class Graph: def __init__(self, n: int, edges: List[List[int]]): self.n = n self.adjList = [[] for _ in range(n)] for a, b, cost in edges: self.adjList[a].append((b, cost)) def addEdge(self, edge: List[int]) -> None: a, b, cost = edge self.adjList[a].append((b, cost)) def shortestPath(self, node1: int, node2: int) -> int: pq = [(0, node1)] dist = [inf]*self.n dist[node1] = 0 while pq: d, node = heappop(pq) if node == node2: return d for neigh, cost in self.adjList[node]: new_dist = cost+d if new_dist<dist[neigh]: dist[neigh] = new_dist heappush(pq, (new_dist, neigh)) return -1 ```