Problem solution · Java

Reachable Nodes In Subdivided Graph

Reachable Nodes In Subdivided Graph: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
61 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeReachable Nodes In Subdivided Graph · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int reachableNodes(int[][] edges, int maxMoves, int n) {    List<Pair<Integer, Integer>>[] graph = new List[n];    int[] dist = new int[n];    Arrays.fill(dist, maxMoves + 1);    Arrays.setAll(graph, i -> new ArrayList<>());     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      final int cnt = edge[2];      graph[u].add(new Pair<>(v, cnt));      graph[v].add(new Pair<>(u, cnt));    }     final int reachableNodes = dijkstra(graph, 0, maxMoves, dist);    int reachableSubnodes = 0;     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      final int cnt = edge[2];      // the number of reachable nodes of `edge` from `u`      final int a = dist[u] > maxMoves ? 0 : Math.min(maxMoves - dist[u], cnt);      // the number of reachable nodes of `edge` from `v`      final int b = dist[v] > maxMoves ? 0 : Math.min(maxMoves - dist[v], cnt);      reachableSubnodes += Math.min(a + b, cnt);    }     return reachableNodes + reachableSubnodes;  }   private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int maxMoves, int[] dist) {    dist[src] = 0;    Queue<Pair<Integer, Integer>> minHeap =        new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {          { offer(new Pair<>(dist[src], src)); } // (d, u)        };     while (!minHeap.isEmpty()) {      final int d = minHeap.peek().getKey();      final int u = minHeap.poll().getValue();      // Already took `maxMoves` to reach `u`, so can't explore anymore.      if (d >= maxMoves)        break;      if (d > dist[u])        continue;      for (Pair<Integer, Integer> pair : graph[u]) {        final int v = pair.getKey();        final int w = pair.getValue();        if (d + w + 1 < dist[v]) {          dist[v] = d + w + 1;          minHeap.offer(new Pair<>(dist[v], v));        }      }    }     return (int) Arrays.stream(dist).filter(d -> d <= maxMoves).count();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗