Statementâ–¼
There are n
cities labeled from
Last year, the Ministry of transport made all roads one-way due to their narrow width. These roads are represented as connections, where each entry connections[i]
This year, a major event will occur in the capital city (city
Note: A solution is guaranteed to exist, meaning that every city can eventually reach city
0 after reordering.
Constraints:
2≤ n
≤5∗104 connections.length
==n−1 connections[i].length
==2 0≤ai​,bi​≤n−1
Solution
This algorithm works because representing the network as a graph with directional information allows us to easily identify which roads are misoriented. By performing a DFS from the capital (city
Now, let’s look at the solution steps below:
Build an adjacency list using a variable
graph
to store the roads and their directional flags.For each connection
[ai​,bi​] inconnections
:Append
(bi​,1) tograph[a
i
]
, where the flag1 indicates that the road goes fromai​ tobi​ and might need to be reversed.Append
(ai​,0) tograph[b
i
]
, where the flag0 represents the reverse edge, which is correctly oriented for the DFS.
Create a set,
visited
, to track which cities have been processed, preventing repeated visits.Call
dfs(0, graph, visited)
to start the DFS from the capital (city0 ) and store the result in a variableresult
.Return
result
as the final answer is the minimum number of road reorientations needed.
Define the DFS function:
Start the DFS from city
0 :Add the current
city
to thevisited
set.Initializes a variable,
reversals
, to count the number of road reversals needed for the subtree rooted at that city.For each neighbor and its associated flag (represented by
need_reverse
) ingraph[city]
:If the neighbor hasn’t been visited, add
need_reverse
toresult
(Asneed_reverse
equals1 if the road needs reversal).Recursively call
dfs(neighbor, graph, visited)
to continue the traversal.
Returns
reversals
.
Let’s look at the following illustration to get a better understanding of the solution: