2
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:6
queue = deque() # from n-node to 1-node9
# 1 step: create dictionary with nodes and nodes' distances to n11
# create dictionary with format (weight, node_to)12
# heap will automatically sort weight and node_to in ascending order14
dct_nd[l] = dct_nd.get(l, []) + [(w, r)]15
dct_nd[r] = dct_nd.get(r, []) + [(w, l)]23
].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change26
el_w, el_nd = heappop(hpf)30
dist_to_n[el_nd] = el_w35
break # you don't need to traverse more if you've reached 1-node36
# other distances will be more than distance of 1-node37
for i_w, i_nd in dct_nd[el_nd]:38
if i_nd not in visited:39
heappush(hpf, (el_w + i_w, i_nd))42
# add to dictionary one more field: number of routes to n43
dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}44
dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 146
# step 2: Dynamic Programming49
# start from n and traverse futher and futher50
nd_prv = queue.popleft()52
for w_cur, nd_cur in dct_nd[nd_prv]:55
and nd_cur in dist_to_n.keys()56
and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]58
# to current node add number of routes from previous node59
dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]60
# !!! careful !!! you need to add modulo operation (as said in the task)61
dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9 + 7))64
return dist_to_n[1][1] # return number of routes for 1-node