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 x1x2, …, 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.

Examples

Example 1:

1
2
3
4
5
6
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.
The nodes that are reachable are highlighted in yellow.

Example 2:

1
2
3
4
Input:
edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
Output:
 23

Example 3:

1
2
3
4
5
Input:
edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
Output:
 1
Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.

Solution

Method 1 – Dijkstra’s Algorithm with Edge Usage Tracking

Intuition

The key idea is to use Dijkstra’s algorithm to find the maximum number of moves left when reaching each node, and for each edge, track how many new subdivided nodes can be reached from both sides. The answer is the sum of all reachable original nodes and all reachable subdivided nodes on each edge.

Approach

  1. Build the graph as an adjacency list.
  2. Use a max-heap to perform Dijkstra’s algorithm, tracking the maximum moves left at each node.
  3. For each edge, track how many subdivided nodes are reached from both ends.
  4. The answer is the number of original nodes reached plus the sum over all edges of min(cnti, used from u + used from v).

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) {
        vector<vector<pair<int,int>>> g(n);
        for (auto& e : edges) {
            g[e[0]].emplace_back(e[1], e[2]);
            g[e[1]].emplace_back(e[0], e[2]);
        }
        vector<int> moves(n, -1);
        priority_queue<pair<int,int>> pq;
        pq.emplace(maxMoves, 0);
        while (!pq.empty()) {
            auto [mv, u] = pq.top(); pq.pop();
            if (moves[u] >= 0) continue;
            moves[u] = mv;
            for (auto& [v, cnt] : g[u]) {
                int left = mv - cnt - 1;
                if (left >= 0 && moves[v] < 0) pq.emplace(left, v);
            }
        }
        int ans = 0;
        for (int x : moves) if (x >= 0) ans++;
        for (auto& e : edges) {
            int a = moves[e[0]] < 0 ? 0 : moves[e[0]];
            int b = moves[e[1]] < 0 ? 0 : moves[e[1]];
            ans += min(e[2], a + b);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
func reachableNodes(edges [][]int, maxMoves int, n int) int {
    g := make([][][2]int, n)
    for _, e := range edges {
        g[e[0]] = append(g[e[0]], [2]int{e[1], e[2]})
        g[e[1]] = append(g[e[1]], [2]int{e[0], e[2]})
    }
    moves := make([]int, n)
    for i := range moves { moves[i] = -1 }
    pq := &hp{}
    heap.Init(pq)
    heap.Push(pq, [2]int{maxMoves, 0})
    for pq.Len() > 0 {
        mv, u := (*pq)[0][0], (*pq)[0][1]
        heap.Pop(pq)
        if moves[u] >= 0 { continue }
        moves[u] = mv
        for _, vw := range g[u] {
            v, cnt := vw[0], vw[1]
            left := mv - cnt - 1
            if left >= 0 && moves[v] < 0 {
                heap.Push(pq, [2]int{left, v})
            }
        }
    }
    ans := 0
    for _, x := range moves {
        if x >= 0 { ans++ }
    }
    for _, e := range edges {
        a, b := 0, 0
        if moves[e[0]] >= 0 { a = moves[e[0]] }
        if moves[e[1]] >= 0 { b = moves[e[1]] }
        if a+b < e[2] {
            ans += a + b
        } else {
            ans += e[2]
        }
    }
    return ans
}
type hp [][2]int
func (h hp) Len() int           { return len(h) }
func (h hp) Less(i, j int) bool { return h[i][0] > h[j][0] }
func (h hp) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(x interface{}) { *h = append(*h, x.([2]int)) }
func (h *hp) Pop() interface{}   { old := *h; x := old[len(old)-1]; *h = old[:len(old)-1]; return x }
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
    public int reachableNodes(int[][] edges, int maxMoves, int n) {
        List<int[]>[] g = new List[n];
        for (int i = 0; i < n; i++) g[i] = new ArrayList<>();
        for (int[] e : edges) {
            g[e[0]].add(new int[]{e[1], e[2]});
            g[e[1]].add(new int[]{e[0], e[2]});
        }
        int[] moves = new int[n];
        Arrays.fill(moves, -1);
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        pq.offer(new int[]{maxMoves, 0});
        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int mv = cur[0], u = cur[1];
            if (moves[u] >= 0) continue;
            moves[u] = mv;
            for (int[] vw : g[u]) {
                int v = vw[0], cnt = vw[1];
                int left = mv - cnt - 1;
                if (left >= 0 && moves[v] < 0) pq.offer(new int[]{left, v});
            }
        }
        int ans = 0;
        for (int x : moves) if (x >= 0) ans++;
        for (int[] e : edges) {
            int a = moves[e[0]] < 0 ? 0 : moves[e[0]];
            int b = moves[e[1]] < 0 ? 0 : moves[e[1]];
            ans += Math.min(e[2], a + b);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    fun reachableNodes(edges: Array<IntArray>, maxMoves: Int, n: Int): Int {
        val g = Array(n) { mutableListOf<Pair<Int,Int>>() }
        for (e in edges) {
            g[e[0]].add(e[1] to e[2])
            g[e[1]].add(e[0] to e[2])
        }
        val moves = IntArray(n) { -1 }
        val pq = java.util.PriorityQueue(compareByDescending<Pair<Int,Int>> { it.first })
        pq.add(maxMoves to 0)
        while (pq.isNotEmpty()) {
            val (mv, u) = pq.remove()
            if (moves[u] >= 0) continue
            moves[u] = mv
            for ((v, cnt) in g[u]) {
                val left = mv - cnt - 1
                if (left >= 0 && moves[v] < 0) pq.add(left to v)
            }
        }
        var ans = moves.count { it >= 0 }
        for (e in edges) {
            val a = if (moves[e[0]] < 0) 0 else moves[e[0]]
            val b = if (moves[e[1]] < 0) 0 else moves[e[1]]
            ans += minOf(e[2], a + b)
        }
        return ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def reachableNodes(self, edges: list[list[int]], maxMoves: int, n: int) -> int:
        import heapq
        g = [[] for _ in range(n)]
        for u, v, cnt in edges:
            g[u].append((v, cnt))
            g[v].append((u, cnt))
        moves = [-1] * n
        h = [(-maxMoves, 0)]
        while h:
            mv, u = heapq.heappop(h)
            mv = -mv
            if moves[u] >= 0:
                continue
            moves[u] = mv
            for v, cnt in g[u]:
                left = mv - cnt - 1
                if left >= 0 and moves[v] < 0:
                    heapq.heappush(h, (-left, v))
        ans = sum(x >= 0 for x in moves)
        for u, v, cnt in edges:
            a = moves[u] if moves[u] >= 0 else 0
            b = moves[v] if moves[v] >= 0 else 0
            ans += min(cnt, a + b)
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
impl Solution {
    pub fn reachable_nodes(edges: Vec<Vec<i32>>, max_moves: i32, n: i32) -> i32 {
        use std::collections::BinaryHeap;
        let n = n as usize;
        let mut g = vec![vec![]; n];
        for e in &edges {
            g[e[0] as usize].push((e[1] as usize, e[2]));
            g[e[1] as usize].push((e[0] as usize, e[2]));
        }
        let mut moves = vec![-1; n];
        let mut h = BinaryHeap::new();
        h.push((max_moves, 0));
        while let Some((mv, u)) = h.pop() {
            if moves[u] >= 0 { continue; }
            moves[u] = mv;
            for &(v, cnt) in &g[u] {
                let left = mv - cnt - 1;
                if left >= 0 && moves[v] < 0 {
                    h.push((left, v));
                }
            }
        }
        let mut ans = moves.iter().filter(|&&x| x >= 0).count() as i32;
        for e in &edges {
            let a = if moves[e[0] as usize] < 0 { 0 } else { moves[e[0] as usize] };
            let b = if moves[e[1] as usize] < 0 { 0 } else { moves[e[1] as usize] };
            ans += std::cmp::min(e[2], a + b);
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    reachableNodes(edges: number[][], maxMoves: number, n: number): number {
        const g: [number, number][][] = Array.from({length: n}, () => []);
        for (const [u, v, cnt] of edges) {
            g[u].push([v, cnt]);
            g[v].push([u, cnt]);
        }
        const moves = Array(n).fill(-1);
        const h: [number, number][] = [[maxMoves, 0]];
        while (h.length) {
            h.sort((a, b) => b[0] - a[0]);
            const [mv, u] = h.shift()!;
            if (moves[u] >= 0) continue;
            moves[u] = mv;
            for (const [v, cnt] of g[u]) {
                const left = mv - cnt - 1;
                if (left >= 0 && moves[v] < 0) h.push([left, v]);
            }
        }
        let ans = moves.filter(x => x >= 0).length;
        for (const [u, v, cnt] of edges) {
            const a = moves[u] < 0 ? 0 : moves[u];
            const b = moves[v] < 0 ? 0 : moves[v];
            ans += Math.min(cnt, a + b);
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(E log N), where E is the number of edges and N is the number of nodes; Dijkstra’s algorithm dominates.
  • 🧺 Space complexity: O(E + N), for the graph and moves array.