Class Solution
-
- All Implemented Interfaces:
public final class Solution2876 - Count Visited Nodes in a Directed Graph\.
Hard
There is a directed graph consisting of
nnodes numbered from0ton - 1andndirected edges.You are given a 0-indexed array
edgeswhereedges[i]indicates that there is an edge from nodeito nodeedges[i].Consider the following process on the graph:
You start from a node
xand keep visiting other nodes through edges until you reach a node that you have already visited before on this same process.
Return an array
answerwhereanswer[i]is the number of different nodes that you will visit if you perform the process starting from nodei.Example 1:
Input: edges = 1,2,0,0
Output: 3,3,3,4
Explanation: We perform the process starting from each node in the following way:
Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3.
Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3.
Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3.
Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4.
Example 2:
Input: edges = 1,2,3,4,0
Output: 5,5,5,5,5
Explanation: Starting from any node we can visit every node in the graph in the process.
Constraints:
n == edges.length<code>2 <= n <= 10<sup>5</sup></code>
0 <= edges[i] <= n - 1edges[i] != i
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntArraycountVisitedNodes(List<Integer> edges)-
-
Method Detail
-
countVisitedNodes
final IntArray countVisitedNodes(List<Integer> edges)
-
-
-
-