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
- 57 lines of C++ from the credited upstream file 2876.cpp.
- 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:3 vector<int> countVisitedNodes(vector<int>& edges) {4 const int n = edges.size();5 vector<int> ans(n);6 vector<int> inDegrees(n);7 vector<bool> seen(n);8 queue<int> q;9 stack<int> stack;10 11 for (const int v : edges)12 ++inDegrees[v];13 14 15 for (int i = 0; i < n; ++i)16 if (inDegrees[i] == 0)17 q.push(i);18 19 20 while (!q.empty()) {21 const int u = q.front();22 q.pop();23 if (--inDegrees[edges[u]] == 0)24 q.push(edges[u]);25 stack.push(u);26 seen[u] = true;27 }28 29 30 for (int i = 0; i < n; ++i)31 if (!seen[i])32 fillCycle(edges, i, seen, ans);33 34 35 while (!stack.empty()) {36 const int u = stack.top();37 stack.pop();38 ans[u] = ans[edges[u]] + 1;39 }40 41 return ans;42 }43 44 private:45 void fillCycle(const vector<int>& edges, int start, vector<bool>& seen,46 vector<int>& ans) {47 int cycleLength = 0;48 for (int u = start; !seen[u]; u = edges[u]) {49 ++cycleLength;50 seen[u] = true;51 }52 ans[start] = cycleLength;53 for (int u = edges[start]; u != start; u = edges[u])54 ans[u] = cycleLength;55 }56};57