Reachable Nodes In Subdivided Graph — LeetCode 882 Python Solution

HardGraphShortest PathHeap (Priority Queue)
Problem
#882
Reading time
4 min

The problem

You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.

Example

Input
edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output
13
Explanation
The edge subdivisions are shown in the image above.

Python solution

Python
class Solution:
    def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
        g = defaultdict(list)
        for u, v, cnt in edges:
            g[u].append((v, cnt + 1))
            g[v].append((u, cnt + 1))
        q = [(0, 0)]
        dist = [0] + [inf] * n
        while q:
            d, u = heappop(q)
            for v, cnt in g[u]:
                if (t := d + cnt) < dist[v]:
                    dist[v] = t
                    q.append((t, v))
        ans = sum(d <= maxMoves for d in dist)
        for u, v, cnt in edges:
            a = min(cnt, max(0, maxMoves - dist[u]))
            b = min(cnt, max(0, maxMoves - dist[v]))
            ans += min(cnt, a + b)
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 882. Reachable Nodes In Subdivided Graph is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 882. Reachable Nodes In Subdivided Graph?
LeetCode 882. Reachable Nodes In Subdivided Graph is rated Hard on LeetCode.
What is the time complexity of LeetCode 882. Reachable Nodes In Subdivided Graph?
The Python solution on this page runs in O(n log n).
What is the space complexity of LeetCode 882. Reachable Nodes In Subdivided Graph?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 882. Reachable Nodes In Subdivided Graph cover?
LeetCode 882. Reachable Nodes In Subdivided Graph is tagged Graph, Shortest Path and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview