Problem Description
Given n cities (numbered from 0 to n - 1) connected by n - 1 directed roads forming a tree, we need to reorient the minimum number of roads so that every city can reach the capital, city 0.
Key Insights
- The underlying graph forms a tree, so there is exactly one unique path between any pair of cities.
- By converting the problem to an undirected graph while keeping track of the original directed edges, we can traverse the tree starting from city 0.
- During traversal, if an edge is oriented away from the current node (i.e. in the original direction), it must be reversed in order for the path to lead to city 0.
- A DFS or BFS can be used to count the minimum number of edge reversals needed.
Space and Time Complexity
Time Complexity: O(n), where n is the number of cities, since we traverse each edge exactly once. Space Complexity: O(n), for storing the graph and the recursion/queue for traversal.
Solution
The approach is to convert the directed tree into an undirected graph while tagging each edge with a flag indicating its original orientation. For each directed edge from a to b:
- Add an edge (b, 1) to a’s list, indicating that if we travel from a to b, the edge is in the original forward direction and will require a reversal.
- Also add an edge (a, 0) to b’s list, which represents the reversed edge that does not require changing if we go from b to a. Starting the traversal from city 0 ensures that every visited edge leading out from 0 must be reversed. We then perform a DFS (or BFS) to visit all the cities while tracking and counting the edges that require reorientation. This method guarantees that all nodes will eventually reach city 0 with a minimal number of changes.