Approach
Breadth-first search
For Count Visited Nodes in a Directed 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
- 52 lines of Java from the credited upstream file 2876.java.
- The implementation visibly relies on sequence storage, work queue.
- 7 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[] countVisitedNodes(List<Integer> edges) {3 final int n = edges.size();4 int[] ans = new int[n];5 int[] inDegrees = new int[n];6 boolean[] seen = new boolean[n];7 Queue<Integer> q = new ArrayDeque<>();8 Stack<Integer> stack = new Stack<>();9 10 for (int v : edges)11 ++inDegrees[v];12 13 14 for (int i = 0; i < n; ++i)15 if (inDegrees[i] == 0)16 q.add(i);17 18 19 while (!q.isEmpty()) {20 final int u = q.poll();21 if (--inDegrees[edges.get(u)] == 0)22 q.add(edges.get(u));23 stack.push(u);24 seen[u] = true;25 }26 27 28 for (int i = 0; i < n; ++i)29 if (!seen[i])30 fillCycle(edges, i, seen, ans);31 32 33 while (!stack.isEmpty()) {34 final int u = stack.pop();35 ans[u] = ans[edges.get(u)] + 1;36 }37 38 return ans;39 }40 41 private void fillCycle(List<Integer> edges, int start, boolean[] seen, int[] ans) {42 int cycleLength = 0;43 for (int u = start; !seen[u]; u = edges.get(u)) {44 ++cycleLength;45 seen[u] = true;46 }47 ans[start] = cycleLength;48 for (int u = edges.get(start); u != start; u = edges.get(u))49 ans[u] = cycleLength;50 }51}52