You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You are given the integer n and an array edges where edges[i] = [u_i, v_i, cnt_i] indicates that there is an edge between nodes u_i and v_i in the original graph, and cnt_i is the total number of new nodes on that edge.
The graph is subdivided: each edge [u_i, v_i, cnt_i] is replaced by a chain of cnt_i new nodes joined by cnt_i + 1 edges, running u_i, x_1, x_2, ..., x_cnt_i, v_i. When cnt_i = 0 the edge stays as it is. The new nodes are not given IDs.
You are also given an integer max_moves, the maximum number of moves you can make. In one move, you can traverse one edge of the subdivided graph.
Starting from node 0, return the number of nodes, original and new, that are reachable from node 0 within at most max_moves moves. The count includes node 0 itself.
Function Signature
def reachable_nodes(edges: list[list[int]], max_moves: int, n: int) -> int:
Rules
-
Each
edges[i]
is a list
[u, v, cnt]
with
u < v
.
-
A node counts once, however many routes reach it. It is reachable when the shortest walk from node
0
to it uses at most
max_moves
moves.
Constraints
-
1 <= n <= 3000
-
0 <= len(edges) <= min(n * (n - 1) / 2, 10^4)
-
len(edges[i]) == 3
-
0 <= u_i < v_i < n
-
There are no multiple edges in the graph.
-
0 <= cnt_i <= 10^4
-
0 <= max_moves <= 10^9
Examples
Input: edges = [[0, 1, 10], [0, 2, 1], [1, 2, 2]], max_moves = 6, n = 3
Output: 13
Node 2 is 2 moves away (through the one new node on edge 0-2) and node 1 is 5 moves away (through node 2), so all 3 original nodes count. Edge 0-1 gives 6 new nodes from node 0's side and 1 from node 1's side, edge 0-2 gives its 1 new node and edge 1-2 gives both of its new nodes, for 3 + 7 + 1 + 2 = 13.
Input: edges = [[0, 1, 4], [1, 2, 6], [0, 2, 8], [1, 3, 1]], max_moves = 10, n = 4
Output: 23
The shortest move counts to nodes 0, 1, 2 and 3 are 0, 5, 9 and 7, all within 10. Every new node is reachable as well (on edge 1-2, node 1 covers 5 of the 6 and node 2 covers the last one), so the answer is 4 + 4 + 6 + 8 + 1 = 23.
Input: edges = [[0, 1, 3], [1, 2, 1]], max_moves = 2, n = 3
Output: 3
Node 1 is 4 moves away and node 2 is 6, so node 0 is the only original node that counts. Two moves along edge 0-1 reach 2 of its 3 new nodes, giving 1 + 2 = 3.