Reorder Routes to Make All Paths Lead to the City Zero

Medium DFS

Problem

Given n cities numbered from 0 to n-1 and a list of directed connections where connections[i] = [a, b] represents a directed edge from city a to city b, return the minimum number of edges that must be reversed so that every city can reach city 0.

  • 2 ≤ n ≤ 5 * 10⁴
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 ≤ connections[i][0], connections[i][1] ≤ n - 1
  • All cities are connected

Example

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3

Starting from city 0, the algorithm builds an undirected graph to explore all cities. It tracks the original direction of edges in a set. When traversing from city 0, it visits neighbors. If the edge from the current city to the neighbor exists in the original direction set, it means this edge must be reversed to allow travel back to city 0, so the count increments. For example, edge (0,1) is directed away from city 0 and must be reversed. Similarly, edges (1,3) and (4,5) must be reversed. The total count is 3.

Approach

Straightforward Solution

A brute-force approach might try all permutations of edge reversals, which is computationally infeasible due to exponential complexity.

Core Observation

The problem reduces to ensuring all nodes can reach node 0 by reversing the minimum number of edges. The key insight is that the original directed edges that point away from node 0 must be reversed, while edges that already point towards node 0 do not need changes.

Path to Optimal

By treating the graph as undirected for traversal and keeping track of original edge directions, the problem becomes a DFS traversal starting from node 0. Whenever the traversal encounters an edge directed away from the current node (according to the original direction), it counts that edge as needing reversal. This approach leverages the connectedness of the graph and the properties of DFS to efficiently count the minimal reversals.

Optimal Approach

Build an undirected graph from the connections to allow traversal in both directions. Store the original directed edges in a set for quick lookup. Perform DFS starting from node 0, marking visited nodes. For each neighbor, if the edge from the current node to the neighbor exists in the original direction set, increment the reversal count. Recursively accumulate the count from all reachable nodes. Return the total count after DFS completes.

Time

O(n)

Each node and edge is visited once during DFS. Building the graph and the set of edges also takes O(n) time.

Space

O(n)

The adjacency list and the set of edges each store O(n) elements. The recursion stack in DFS can go up to O(n) in the worst case.

Pattern Spotlight

DFS (Graph Traversal with Edge Direction Tracking)

When needing to reorient edges to ensure reachability to a root node, convert the graph to undirected for traversal while tracking original edge directions; count reversals when traversing edges that point away from the root.

Solution

1class Solution:
2 def minReorder(self, n: int, connections: List[List[int]]) -> int:
3 roads = set()
4 graph = defaultdict(list)
5 for x, y in connections:
6 graph[x].append(y)
7 graph[y].append(x)
8 roads.add((x, y))
9
10 def dfs(node):
11 ans = 0
12 for neighbor in graph[node]:
13 if neighbor not in seen:
14 if (node, neighbor) in roads:
15 ans += 1
16 seen.add(neighbor)
17 ans += dfs(neighbor)
18
19 return ans
20
21 seen = {0}
22 return dfs(0)

Step-by-Step Solution

1

Build Undirected Graph and Track Original Directed Edges

3roads = set()
4graph = defaultdict(list)
5for x, y in connections:
6 graph[x].append(y)
7 graph[y].append(x)
8 roads.add((x, y))

Objective

To construct a data structure that supports traversal in both directions while remembering the original edge directions.

Key Insight

By creating an undirected graph, the algorithm can explore all nodes from the root without missing any due to direction constraints. Storing the original directed edges in a set allows quick determination of whether an edge needs reversal during traversal.

Interview Quick-Check

Core Logic

The undirected graph enables full traversal, while the set of original edges identifies which edges are directed away from the current node and thus require reversal.

Common Pitfalls & Bugs

Forgetting to add edges in both directions to the graph or failing to track original edge directions leads to incorrect reversal counts.

2

Perform DFS Traversal to Count Required Edge Reversals

10def dfs(node):
11 ans = 0
12 for neighbor in graph[node]:
13 if neighbor not in seen:
14 if (node, neighbor) in roads:
15 ans += 1
16 seen.add(neighbor)
17 ans += dfs(neighbor)
19 return ans
21seen = {0}
22return dfs(0)

Objective

To recursively explore all reachable nodes from city 0, counting edges that must be reversed to ensure all paths lead to city 0.

Key Insight

DFS explores the graph starting from city 0, marking visited nodes to avoid cycles. When moving from a node to its neighbor, if the original edge points away from the current node, it must be reversed. Accumulating these counts during recursion yields the minimal number of reversals needed.

Interview Quick-Check

Core Logic

DFS visits each node once, and for each neighbor, checks if the edge direction requires reversal by querying the original edges set.

State & Boundaries

The visited set prevents revisiting nodes, ensuring termination and correctness.

Common Pitfalls & Bugs

Not adding neighbors to the visited set before recursive calls can cause infinite loops or double counting.

Line Analysis

This solution has 4 Critical lines interviewers watch for.

Line 14 Critical
if (node, neighbor) in roads:

Check if the edge from the current node to the neighbor exists in the original directed edges set.

If this edge exists, it means the edge is directed away from the current node and must be reversed to allow travel back to node 0.

Line 13 Critical
if neighbor not in seen:

Check if the neighbor has not been visited yet.

This condition prevents revisiting nodes, avoiding infinite recursion and double counting.

Line 15 Critical
ans += 1

Increment the reversal count because this edge must be reversed.

Counting this edge here ensures the final answer reflects the minimal number of reversals needed to make all paths lead to node 0.

Line 17 Critical
ans += dfs(neighbor)

Recursively call DFS on the neighbor and add its reversal count to the current count.

This recursive accumulation aggregates reversal counts from all reachable nodes, ensuring the total count is correct.

Line 3 Core
roads = set()

Initialize a set to store the original directed edges for quick lookup.

This set allows O(1) checks to determine if an edge is directed from node x to node y, which is critical for deciding if an edge needs to be reversed.

Line 8 Core
roads.add((x, y))

Add the original directed edge (x, y) to the roads set.

Storing the original direction allows the algorithm to detect edges that must be reversed during DFS traversal.

Line 16 Core
seen.add(neighbor)

Mark the neighbor as visited to avoid revisiting.

Adding the neighbor to the visited set before recursion prevents cycles and repeated counting of edges.

Line 19 Core
return ans

Return the total count of edges to reverse from this node's subtree.

Returning the accumulated count allows the recursion to propagate the total number of reversals up to the root call.

Line 22 Core
return dfs(0)

Invoke DFS starting from node 0 and return the total reversal count.

This call triggers the entire traversal and counting process, producing the final answer.

Line 4 Core
graph = defaultdict(list)

Initialize an adjacency list as a default dictionary of lists to represent the undirected graph.

Using a defaultdict simplifies graph construction and supports efficient neighbor lookups during traversal.

Line 6 Core
graph[x].append(y)

Add y as a neighbor of x in the undirected graph.

Adding this edge supports traversal from x to y regardless of original direction, enabling full graph exploration.

Line 7 Core
graph[y].append(x)

Add x as a neighbor of y in the undirected graph.

Adding this reverse edge ensures traversal can proceed from y to x, which is essential for DFS to reach all nodes.

Line 12 Core
for neighbor in graph[node]:

Iterate over all neighbors of the current node in the undirected graph.

Exploring all neighbors ensures the entire connected component is traversed, which is necessary to count all required reversals.

Line 21 Core
seen = {0}

Initialize the visited set with node 0 to start DFS traversal.

Starting with node 0 visited ensures the traversal begins from the root city and prevents revisiting it.

Line 10 Standard
def dfs(node):

Define the DFS function that returns the count of edges to reverse starting from the given node.

Encapsulating the traversal and counting logic in a recursive function enables clean, modular exploration of the graph.

Line 5 Standard
for x, y in connections:

Iterate over each directed edge (x, y) in the connections list.

Processing each edge is necessary to build the undirected graph and track original directions.

Line 11 Standard
ans = 0

Initialize the reversal count to zero for the current node.

This accumulator tracks the number of edges that must be reversed in the subtree rooted at the current node.

Test Your Understanding

Why does traversing the graph as undirected and checking the original edge direction allow counting the minimum number of reversals?

Because traversing undirected ensures all nodes are reachable in the traversal, and checking if the edge points away from the current node identifies exactly those edges that must be reversed to enable travel back to node 0, ensuring minimal reversals.

Related Problems

DFS pattern

Don't just read it. Drill it.

Reconstruct Reorder Routes to Make All Paths Lead to the City Zero from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Reorder Routes to Make All Paths Lead to the City Zero drill

or drill a free problem