Problem Description
Given n
cities numbered from 0
to n - 1
and n - 1
roads represented by connections
where connections[i] = [a_i, b_i]
indicates a one-way road from city a_i
to city b_i
, the task is to reorient some roads such that every city can reach city 0
. The goal is to return the minimum number of edges that need to be changed.
Key Insights
- The cities and roads form a tree structure since there are
n
nodes (cities) andn - 1
edges (roads). - Each city must eventually reach city
0
, which is the root of the tree. - Reorienting a road from
b
toa
is necessary if the current road goes froma
tob
and cityb
is not directly leading to city0
. - A depth-first search (DFS) or breadth-first search (BFS) can be used to traverse the tree and count the required reorientations.
Space and Time Complexity
Time Complexity: O(n) - We visit each edge once during the traversal. Space Complexity: O(n) - For storing the graph representation and recursion stack (in the case of DFS).
Solution
To solve the problem, we represent the cities and roads as a directed graph using an adjacency list. We then perform a DFS traversal starting from city 0
, counting how many edges need to be reversed to ensure all cities can reach city 0
. During the traversal, we check the direction of each edge and increment our count whenever we encounter an edge that does not point towards city 0
.