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
- 54 lines of Python from the credited upstream file 2876.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit 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 def countVisitedNodes(self, edges: list[int]) -> list[int]:3 n = len(edges)4 ans = [0] * n5 inDegrees = [0] * n6 seen = [False] * n7 stack = []8 9 for v in edges:10 inDegrees[v] += 111 12 13 q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0])14 15 16 while q:17 u = q.popleft()18 inDegrees[edges[u]] -= 119 if inDegrees[edges[u]] == 0:20 q.append(edges[u])21 stack.append(u)22 seen[u] = True23 24 25 for i in range(n):26 if not seen[i]:27 self._fillCycle(edges, i, seen, ans)28 29 30 while stack:31 u = stack.pop()32 ans[u] = ans[edges[u]] + 133 34 return ans35 36 def _fillCycle(37 self,38 edges: list[int],39 start: int,40 seen: list[bool],41 ans: list[int],42 ) -> None:43 cycleLength = 044 u = start45 while not seen[u]:46 cycleLength += 147 seen[u] = True48 u = edges[u]49 ans[start] = cycleLength50 u = edges[start]51 while u != start:52 ans[u] = cycleLength53 u = edges[u]54