Class Solution
-
- All Implemented Interfaces:
public final class Solution2858 - Minimum Edge Reversals So Every Node Is Reachable.
Hard
There is a simple directed graph with
nnodes labeled from0ton - 1. The graph would form a tree if its edges were bi-directional.You are given an integer
nand a 2D integer arrayedges, where <code>edgesi = u<sub>i</sub>, v<sub>i</sub></code> represents a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.An edge reversal changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.
For every node
iin the range[0, n - 1], your task is to independently calculate the minimum number of edge reversals required so it is possible to reach any other node starting from nodeithrough a sequence of directed edges.Return an integer array
answer, whereanswer[i]is the minimum number of edge reversals required so it is possible to reach any other node starting from nodeithrough a sequence of directed edges.Example 1:
Input: n = 4, edges = [2,0,2,1,1,3]
Output: 1,1,0,2
Explanation: The image above shows the graph formed by the edges.
For node 0: after reversing the edge 2,0, it is possible to reach any other node starting from node 0.
So, answer0 = 1.
For node 1: after reversing the edge 2,1, it is possible to reach any other node starting from node 1.
So, answer1 = 1.
For node 2: it is already possible to reach any other node starting from node 2.
So, answer2 = 0.
For node 3: after reversing the edges 1,3 and 2,1, it is possible to reach any other node starting from node 3.
So, answer3 = 2.
Example 2:
Input: n = 3, edges = [1,2,2,0]
Output: 2,0,1
Explanation: The image above shows the graph formed by the edges.
For node 0: after reversing the edges 2,0 and 1,2, it is possible to reach any other node starting from node 0.
So, answer0 = 2.
For node 1: it is already possible to reach any other node starting from node 1.
So, answer1 = 0.
For node 2: after reversing the edge 1, 2, it is possible to reach any other node starting from node 2.
So, answer2 = 1.
Constraints:
<code>2 <= n <= 10<sup>5</sup></code>
edges.length == n - 1edges[i].length == 2<code>0 <= u<sub>i</sub> == edges0< n</code>
<code>0 <= v<sub>i</sub> == edges1< n</code>
<code>u<sub>i</sub> != v<sub>i</sub></code>
The input is generated such that if the edges were bi-directional, the graph would be a tree.