There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.

A path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 &lt;= i &lt;= k-1.

The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) &gt; distanceToLastNode(zi+1) where 0 &lt;= i &lt;= k-1.

Return the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.

&nbsp;
Example 1:

Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
Output: 3
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
1) 1 --&gt; 2 --&gt; 5
2) 1 --&gt; 2 --&gt; 3 --&gt; 5
3) 1 --&gt; 3 --&gt; 5


Example 2:

Input: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
Output: 1
Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --&gt; 3 --&gt; 7.


&nbsp;
Constraints:


	1 &lt;= n &lt;= 2 * 104
	n - 1 &lt;= edges.length &lt;= 4 * 104
	edges[i].length == 3
	1 &lt;= ui, vi &lt;= n
	ui != vi
	1 &lt;= weighti &lt;= 105
	There is at most one edge between any two nodes.
	There is at least one path between any two nodes.


class Solution:
    def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
        
        dct_nd    = {}
        dist_to_n = {}
        queue     = deque() # from n-node to 1-node
        visited   = set()
        
        # 1 step: create dictionary with nodes and nodes' distances to n

        # create dictionary with format (weight, node_to)
        # heap will automatically sort weight and node_to in ascending order
        for l, r, w in edges:
            dct_nd[l] = dct_nd.get(l, []) + [(w, r)]
            dct_nd[r] = dct_nd.get(r, []) + [(w, l)]
        
        dist_to_n[n] = 0
        queue.append(n)
        visited.add(n)
        
        hpf = dct_nd[n].copy()   # without '.copy()' hpf will be only pointer and dct_nd[n] could change
        heapify(hpf)
        while hpf:
            el_w, el_nd = heappop(hpf)
            if el_nd in visited:   continue
            
            dist_to_n[el_nd] = el_w
            visited.add(el_nd)
            queue.append(el_nd)

            if el_nd == 1:         break  # you don't need to traverse more if you've reached 1-node
                                          # other distances will be more than distance of 1-node
            for (i_w, i_nd) in dct_nd[el_nd]:
                if i_nd not in visited:
                    heappush(hpf, (el_w + i_w, i_nd))
        # step 1: end

        # add to dictionary one more field: number of routes to n
        dist_to_n = {k: [v, 0]   for k, v in dist_to_n.items()}
        dist_to_n[n] = [dist_to_n[n][0], 1]  # for n-node number of routes = 1
        
        # step 2: Dynamic Programming
        visited.clear()
        while queue:
            # start from n and traverse futher and futher
            nd_prv = queue.popleft()
            visited.add(nd_prv)
            for (w_cur, nd_cur) in dct_nd[nd_prv]:
                if nd_cur not in visited           and   \
                   nd_cur     in dist_to_n.keys()  and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:
                    # to current node add number of routes from previous node
                    dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]
                    # !!! careful !!! you need to add modulo operation (as said in the task)
                    dist_to_n[nd_cur][1]  = int(dist_to_n[nd_cur][1] % (1e9+7))
        # step 2: End
        
        return dist_to_n[1][1] # return number of routes for 1-node
class Solution {
    int dp[];
    //We use memoization
    public int countRestrictedPaths(int n, int[][] edges) {
        int[] dist = new int[n+1];
        dp = new int[n+1];
        Arrays.fill(dp,-1);
        Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
        //Create the graph from input edges
        for(int[] e : edges){
            graph.putIfAbsent(e[0], new HashMap<>());
            graph.putIfAbsent(e[1], new HashMap<>());
            graph.get(e[0]).put(e[1],e[2]);
            graph.get(e[1]).put(e[0],e[2]);
        }
        //Single source shortest distance - something like Dijkstra's
        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));
        int[] base = new int[2];
        base[0]=n;
        pq.offer(base);
        while(!pq.isEmpty()){
            int[] currNode = pq.poll();

            for(Map.Entry<Integer, Integer> neighbour: graph.get(currNode[0]).entrySet()){
                int node = neighbour.getKey();
                int d = neighbour.getValue()+currNode[1];
                if(node==n) continue;
                //Select only those neighbours, whose new distance is less than existing distance
                //New distance = distance of currNode from n + weight of edge between currNode and neighbour

                if( dist[node]==0 || d < dist[node]){
                    int[] newNode = new int[2];
                    newNode[0]=node;
                    newNode[1]=d;
                    pq.offer(newNode);
                    dist[node]= d;
                }
            }
        }

        return find(1,graph,n,dist);
    }
    //This method traverses all the paths from source node to n though it's neigbours
    private int find(int node, Map<Integer, Map<Integer, Integer>> graph, int n, int[] dist ){
        if(node==n){
            return 1;
        }

        //Memoization avoid computaion of common subproblems.
        if(dp[node]!=-1) return dp[node];

        int ans = 0;
        for(Map.Entry<Integer, Integer> neighbour: graph.get(node).entrySet()){
                int currNode = neighbour.getKey();
                int d = dist[currNode];
                if( dist[node] > d){
                    ans = (ans + find(currNode, graph, n, dist)) % 1000000007;
            }
        }

        return dp[node] = ans;
    }
}
typedef pair<int, int> pii;
class Solution {
public:
    int countRestrictedPaths(int n, vector<vector<int>>& edges) {
        unordered_map<int, vector<pair<int, int>>> gp;
        for (auto& edge : edges) {
            gp[edge[0]].push_back({edge[1], edge[2]});
            gp[edge[1]].push_back({edge[0], edge[2]});
        }

        vector<int> dist(n + 1, INT_MAX);
        priority_queue<pii, vector<pii>, greater<pii> > pq;
        pq.push({0, n});
        dist[n] = 0;

        int u, v, w;
        while (!pq.empty()) {
            pii p = pq.top(); pq.pop();
            u = p.second;
            for (auto& to : gp[u]) {
                v = to.first, w = to.second;
                if (dist[v] > dist[u] + w) {
                    dist[v] = dist[u] + w;
                    pq.push({dist[v], v});
                }
            }
        }
        vector<int> dp(n + 1, -1);
        return dfs(gp, n, dp, dist);
    }

    int dfs(unordered_map<int, vector<pair<int, int>>>& gp, int s, vector<int>& dp, vector<int>& dist) {
        int mod = 1e9+7;
        if (s == 1) return 1;
        if (dp[s] != -1) return dp[s];
        int sum = 0, weight, val;
        for (auto& n : gp[s]) {
            weight = dist[s];
            val = dist[n.first];
            if (val > weight) {
                sum = (sum % mod + dfs(gp, n.first, dp, dist) % mod) % mod;
            }
        }
        return dp[s] = sum % mod;
    }
};
var countRestrictedPaths = function(n, edges) {
    // create an adjacency list to store the neighbors with weight for each node
    const adjList = new Array(n + 1).fill(null).map(() => new Array(0));
    for (const [node1, node2, weight] of edges) {
        adjList[node1].push([node2, weight]);
        adjList[node2].push([node1, weight]);
    }
    
    // using djikstras algorithm
    // find the shortest path from n to each node
    const nodeToShortestPathDistance = {}
    const heap = new Heap();
    heap.push([n, 0])
    let numNodeSeen = 0;
    while (numNodeSeen < n) {
        const [node, culmativeWeight] = heap.pop();
        if (nodeToShortestPathDistance.hasOwnProperty(node)) {
            continue;
        }
        nodeToShortestPathDistance[node] = culmativeWeight;
        numNodeSeen++;
        for (const [neighbor, edgeWeight] of adjList[node]) {
            if (nodeToShortestPathDistance.hasOwnProperty(neighbor)) {
                continue;
            }
            heap.push([neighbor, edgeWeight + culmativeWeight]);
        }
    }
    

    // do a DFS caching the number of paths for each node
    // so that we don't need to redo the number of paths again
    // when we visit that node through another path
    const nodeToNumPaths = {};
    const dfs = (node) => {
        if (node === n) return 1;
        if (nodeToNumPaths.hasOwnProperty(node)) {
            return nodeToNumPaths[node];
        }
        let count = 0;
        for (const [neighbor, weight] of adjList[node]) {
            if (nodeToShortestPathDistance[node] > nodeToShortestPathDistance[neighbor]) {
                count += dfs(neighbor);
            }
        }
        return nodeToNumPaths[node] = count % 1000000007;
    }
    return dfs(1);
};

class Heap {
    constructor() {
        this.store = [];
    }
    
    peak() {
        return this.store[0];
    }
    
    size() {
        return this.store.length;
    }
    
    pop() {
        if (this.store.length < 2) {
            return this.store.pop();
        }
        const result = this.store[0];
        this.store[0] = this.store.pop();
        this.heapifyDown(0);
        return result;
    }
    
    push(val) {
        this.store.push(val);
        this.heapifyUp(this.store.length - 1);
    }
    
    heapifyUp(child) {
        while (child) {
            const parent = Math.floor((child - 1) / 2);
            if (this.shouldSwap(child, parent)) {
                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
                child = parent;
            } else {
                return child;
            }
        }
    }
    
    heapifyDown(parent) {
        while (true) {
            let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());
            if (this.shouldSwap(child2, child)) {
                child = child2
            }
            if (this.shouldSwap(child, parent)) {
                [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]
                parent = child;
            } else {
                return parent;
            }
        }
    }
    
    shouldSwap(child, parent) {
        return child && this.store[child][1] < this.store[parent][1];
    }
}
Number of Restricted Paths From First to Last Node