Solution: Reorder Routes to Make All Paths Lead to the City Zero
Let’s solve the Reorder Routes to Make All Paths Lead to the City Zero problem using the Graphs pattern.
We'll cover the following
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
after reordering.
Constraints:
n
connections.length
connections[i].length
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
in connections
:Append
to graph[a
i
]
, where the flagindicates that the road goes from to and might need to be reversed. Append
to graph[b
i
]
, where the flagrepresents 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 (city) and store the result in a variable result
.Return
result
as the final answer is the minimum number of road reorientations needed.
Define the DFS function:
Start the DFS from city
: 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
needReverse
) ingraph[city]
:If the neighbor hasn’t been visited, add
needReverse
toresult
(AsneedReverse
equalsif 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:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.