Reorder Routes to Make All Paths Lead to the City Zero (LeetCode 1466): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Graph

The roads form a tree with one-way edges. Find the fewest roads to reverse so that every city can drive to city 0.

Intuition

Because the roads form a tree, each city has exactly one route to 0 once directions are ignored. So every road has one correct direction: toward 0.

Start at 0 and walk outward. When you cross a road from a city you already reached into a new city, that road must point from the new city back to the old one.

If the road was originally built the other way, pointing away from 0, it has to be flipped. Roads already pointing inward cost nothing.

So the answer is simply the number of roads you cross in their original direction during a traversal from 0. Store each road in both cities' lists with a tag telling which way it really points.

Approach: BFS from city 0 with direction tags

  1. For each road a -> b, append (b, 1) to graph[a] and (a, 0) to graph[b]. Tag 1 means the road points away from the city whose list holds it.
  2. Mark 0 as seen and put it in a queue.
  3. Pop a city. For each unseen neighbour, mark it seen, add the tag to changes and push it.
  4. When the queue is empty, return changes.

Step-by-step example

n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
  1. From 0, the road 0 -> 1 points away from 0, so it is flipped (changes = 1). The road 4 -> 0 already points into 0, so it stays.
  2. From 1, the road 1 -> 3 points away from 1, flip it (changes = 2).
  3. From 4, the road 4 -> 5 points away from 4, flip it (changes = 3).
  4. From 3, the road 2 -> 3 already leads into 3, keep it.
  5. Every city is reached, so the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def minReorder(self, n: int, connections: List[List[int]]) -> int:
3        graph = [[] for _ in range(n)]
4        for a, b in connections:
5            graph[a].append((b, 1))
6            graph[b].append((a, 0))
7        seen = [False] * n
8        seen[0] = True
9        queue = deque([0])
10        changes = 0
11        while queue:
12            city = queue.popleft()
13            for nxt, away in graph[city]:
14                if not seen[nxt]:
15                    seen[nxt] = True
16                    changes += away
17                    queue.append(nxt)
18        return changes
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each city is visited once and each road is examined twice, once from each end.

Space

O(n)

The adjacency lists, the seen array and the queue each hold O(n) entries.

Other approaches

DFS with the same tags (time O(n), space O(n))

A recursive or stack-based DFS from 0 counts the same roads. Use an explicit stack in languages with small recursion limits, since a chain of 5 * 10^4 cities is deep.

Set of original edges (time O(n), space O(n))

Build an undirected adjacency list plus a hash set of (a, b) pairs, and check membership when moving from a to b. Simple but slower because of hashing.

Common mistakes

  • Only traversing roads in their original direction. City 0 might have no outgoing roads at all, so the traversal must use both directions.
  • Counting the inward roads instead of the outward ones. Moving from parent to child over a road that points parent -> child is the one that needs flipping.
  • Recursive DFS on a long chain can overflow the stack in Python or Java. BFS avoids that.

Frequently asked questions

Why is a greedy count optimal?

In a tree every city has a single path to 0, so each road's required direction is forced. No choice exists; you just count the roads that disagree.

Does BFS order matter?

No. Any traversal from 0 crosses every road exactly once going outward, so BFS and DFS give the same count.

What if the roads did not form a tree?

Then a road's required direction would not be forced and the problem becomes much harder. The n - 1 roads and the guarantee of connectivity are what make this simple.