Approach
Breadth-first search
For Reachable Nodes In Subdivided Graph, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 61 lines of Java from the credited upstream file 882.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int reachableNodes(int[][] edges, int maxMoves, int n) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 int[] dist = new int[n];5 Arrays.fill(dist, maxMoves + 1);6 Arrays.setAll(graph, i -> new ArrayList<>());7 8 for (int[] edge : edges) {9 final int u = edge[0];10 final int v = edge[1];11 final int cnt = edge[2];12 graph[u].add(new Pair<>(v, cnt));13 graph[v].add(new Pair<>(u, cnt));14 }15 16 final int reachableNodes = dijkstra(graph, 0, maxMoves, dist);17 int reachableSubnodes = 0;18 19 for (int[] edge : edges) {20 final int u = edge[0];21 final int v = edge[1];22 final int cnt = edge[2];23 24 final int a = dist[u] > maxMoves ? 0 : Math.min(maxMoves - dist[u], cnt);25 26 final int b = dist[v] > maxMoves ? 0 : Math.min(maxMoves - dist[v], cnt);27 reachableSubnodes += Math.min(a + b, cnt);28 }29 30 return reachableNodes + reachableSubnodes;31 }32 33 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int maxMoves, int[] dist) {34 dist[src] = 0;35 Queue<Pair<Integer, Integer>> minHeap =36 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {37 { offer(new Pair<>(dist[src], src)); } 38 };39 40 while (!minHeap.isEmpty()) {41 final int d = minHeap.peek().getKey();42 final int u = minHeap.poll().getValue();43 44 if (d >= maxMoves)45 break;46 if (d > dist[u])47 continue;48 for (Pair<Integer, Integer> pair : graph[u]) {49 final int v = pair.getKey();50 final int w = pair.getValue();51 if (d + w + 1 < dist[v]) {52 dist[v] = d + w + 1;53 minHeap.offer(new Pair<>(dist[v], v));54 }55 }56 }57 58 return (int) Arrays.stream(dist).filter(d -> d <= maxMoves).count();59 }60}61