Reachable Nodes In Subdivided Graph - 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.

The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.

To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].

In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.

Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.

Input & Output

Example 1 — Basic Case
$ Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
💡 Note: From node 0: can reach node 2 (distance 2), then reach some nodes on edge [0,1] and [1,2]. Total reachable includes all original nodes and several subdivided nodes.
Example 2 — Simple Path
$ Input: edges = [[0,1,4],[1,2,6]], maxMoves = 10, n = 3
Output: 23
💡 Note: Can traverse the entire path 0→1→2 and reach most subdivided nodes along the way within 10 moves.
Example 3 — No Subdivisions
$ Input: edges = [[1,2,0],[2,3,0]], maxMoves = 3, n = 4
Output: 1
💡 Note: Starting from node 0, cannot reach any other nodes since node 0 is isolated. Only node 0 itself is reachable.

Constraints

  • 0 ≤ edges.length ≤ 104
  • 0 ≤ ui, vi < n
  • There are no multiple edges in the graph
  • 0 ≤ cnti ≤ 104
  • 0 ≤ maxMoves ≤ 109
  • 1 ≤ n ≤ 3000

Visualization

Tap to expand
Reachable Nodes in Subdivided GraphOriginal Graph01cnt=2Subdivided Graph0x1x21dist=0dist=1dist=2dist=3With maxMoves = 6✓ All 4 nodes are reachableTotal reachable: 2 original + 2 subdivided = 4Algorithm: Use Dijkstra to find shortest paths, then count reachable nodes
Understanding the Visualization
1
Original Graph
Graph with edges containing subdivision counts
2
Subdivided Graph
Each edge is replaced with a chain of intermediate nodes
3
Reachable Nodes
Count all nodes reachable from node 0 within maxMoves distance
Key Takeaway
🎯 Key Insight: Use Dijkstra's algorithm to efficiently find shortest distances to original nodes, then calculate how many subdivided nodes are reachable on each edge
Asked in
Google 15 Facebook 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen