<p>There is an undirected weighted connected graph. You are given a positive integer <code>n</code> which denotes that the graph has <code>n</code> nodes labeled from <code>1</code> to <code>n</code>, and an array <code>edges</code> where each <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, weight<sub>i</sub>]</code> denotes that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with weight equal to <code>weight<sub>i</sub></code>.</p>

<p>A path from node <code>start</code> to node <code>end</code> is a sequence of nodes <code>[z<sub>0</sub>, z<sub>1</sub>,<sub> </sub>z<sub>2</sub>, ..., z<sub>k</sub>]</code> such that <code>z<sub>0 </sub>= start</code> and <code>z<sub>k</sub> = end</code> and there is an edge between <code>z<sub>i</sub></code> and <code>z<sub>i+1</sub></code> where <code>0 &lt;= i &lt;= k-1</code>.</p>

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

<p>Return <em>the number of restricted paths from node</em> <code>1</code> <em>to node</em> <code>n</code>. Since that number may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" style="width: 351px; height: 341px;" />
<pre>
<strong>Input:</strong> n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each circle contains the node number in black and its <code>distanceToLastNode value in blue. </code>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
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" style="width: 356px; height: 401px;" />
<pre>
<strong>Input:</strong> 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]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each circle contains the node number in black and its <code>distanceToLastNode value in blue. </code>The only restricted path is 1 --&gt; 3 --&gt; 7.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>n - 1 &lt;= edges.length &lt;= 4 * 10<sup>4</sup></code></li>
	<li><code>edges[i].length == 3</code></li>
	<li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li>
	<li><code>u<sub>i </sub>!= v<sub>i</sub></code></li>
	<li><code>1 &lt;= weight<sub>i</sub> &lt;= 10<sup>5</sup></code></li>
	<li>There is at most one edge between any two nodes.</li>
	<li>There is at least one path between any two nodes.</li>
</ul>

class Solution:
    def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
        # will call distanceToLastNode values "blue" values
        # idea: assume the distanceToLastNode values are known, all is left is to
        # calc the number of paths from to n. How many paths is this? Any node
        # with a smaller blue value is a possibility. For each neighbor with a 
        # smaller blue value, add the number of ways that child can reach n.
        
        # For faster calculations, check if a node's number of restricted paths 
        # has previously been found. If not, find it and save it. If it has, simply
        # return that value.

        # Base cases: number of restricted paths from n starting from n is 1.
        # If a node is not n and has not neighbors with smaller blue values, it has 0
        # restricted paths to node.

        # Now, how to find blue values? Blue values are shortest paths to node.
        # This could be done running a shortest path algo like Dijkstra's from each
        # node. However, this may result in many overlapping paths (in Example 1,
        # 4 goes through 1 which might go through 2 which might go through 
        #  3 then to 5. 1 will go through 2 then through 3... 2 will go to 3 then to 5
        # ...). How can this be avoided? Since the paths are bidirectional, we can 
        # instead start from 5 and find the shortest path to all other nodes. Each
        # edge and node is only visited once.


        import heapq            

        # make adjacency list of graph
        graph = dict()
        for nodeA, nodeB, weight in edges:
            nodeA_dict = graph.get(nodeA, dict())
            nodeA_dict[nodeB] = weight
            graph[nodeA] = nodeA_dict

            nodeB_dict = graph.get(nodeB, dict())
            nodeB_dict[nodeA] = weight
            graph[nodeB] = nodeB_dict

        shortest_path_from_n = dict()

        # distance to n is 0
        heap = [(0, n)]

        while len(heap) > 0:
            cost, current = heapq.heappop(heap)
            
            # if already found shortest path, no need to consider current node. Note
            # that this works because Dijkstra's only states the path cost to a node
            # whenever it is the cheapest possible. 
            
            if shortest_path_from_n.get(current, None) is not None:
                continue

            shortest_path_from_n[current] = cost
            
            current_edges = graph.get(current, dict())

            for neighbor, cost_from_current in current_edges.items():
                if shortest_path_from_n.get(current, None) is not None:
                    heapq.heappush(heap, (cost + cost_from_current, neighbor))


        restricted_paths = dict()
        restricted_paths[n] = 1

        def find_restricted_paths(current):
            if restricted_paths.get(current, None) is not None:
                return restricted_paths[current]

            total_restricted_paths = 0

            # Note: usually with traversal, especially with bidirectional edges,
            # you want to keep track of visited nodes so you don't keep going back
            # to them infinitely. In this case, however, we only care and visit
            # nodes with a smaller blue value. Since we visit smaller blue values nodes,
            # that node will not try to visit any node used along the path to get to it,
            # since those nodes must all have had larger blue values. Essentially, because
            # there is no case where 2 nodes can't both have smaller blue values than
            # each other, at max only one can visit the other, and the other way will not
            # work, no infinite loop
            
            current_dict = graph.get(current, dict())

            for neighbor in current_dict.keys():
                if shortest_path_from_n.get(current, float("inf")) > shortest_path_from_n.get(neighbor, float("inf")):
                    total_restricted_paths += find_restricted_paths(neighbor)

            restricted_paths[current] = total_restricted_paths
            return total_restricted_paths


        return find_restricted_paths(1) % (10 ** 9 + 7)


1714