Home
DSA Patterns
Graphs (Topological Sort)
Reorder Routes to Make All Paths Lead to the City Zero
Reorder Routes to Make All Paths Lead to the City Zero
Reorder Routes to Make All Paths Lead to the City Zero: the one-way roads between n cities form a tree. Count the fewest roads to reverse so every city can reach city 0: DFS from 0 and count the roads that point away from it.
Problem Understanding
Reorder Routes to Make All Paths Lead to the City Zero (LeetCode 1466): there are n cities and n − 1 one-way roads, connections[i] = [a, b] for a road from a to b, and ignoring direction they connect every city (a tree). Return the minimum number of roads to reverse so that every city can reach city 0.
Examples: n = 6, [[0,1],[1,3],[2,3],[4,0],[4,5]] → 3; n = 5, [[1,0],[1,2],[3,2],[3,4]] → 2; n = 3, [[1,0],[2,0]] → 0.
The Intuition: Walk Away From 0, Count Roads Going Your Way
Picture the tree hanging from city 0. Every road should point up, toward 0. A search that starts at 0 always moves down, away from 0, so any road it walks in the road’s own direction is pointing down and must be flipped.
- Store each road twice:
a → bgoes into a’s list as(b, 1)and into b’s list as(a, 0). The 1 means "walking this follows the road". - DFS from city 0, ignoring direction, visiting each city once.
- Add the mark of every road you walk. Roads marked 1 point away from 0 and need reversing.
It is a plain graph DFS, like Keys and Rooms, with one bit of extra information on each edge. Number of Provinces uses the same search on an undirected graph.
Reorder Routes to Make All Paths Lead to the City Zero Visualization
CITY 0 ON THE LEFT · GREEN = ALREADY LEADS TO 0 · RED = REVERSED
BUILD BOTH-WAY LISTS
city
:
reversed
0
Answer
:
stack (top last)
Store every road in both cities' lists: 1 where it leaves the city, 0 where it arrives. Start at city 0
Next
Pop city 0: walk each road to a city not seen yet, away from 0
roads
n
City 0 is on the left and each column to the right is one road further from it, so a road that leads to 0 points left. As the DFS walks a road it turns green if it already points to 0, or is redrawn pointing left in red if it has to be reversed. Try All away, where every road is reversed, and Example 3, where none is.
Reorder Routes to Make All Paths Lead to the City Zero Dry Run
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]].
| Pop city | Road walked | Direction | Reversed so far |
|---|---|---|---|
| 0 | 0 → 1 | away from 0: reverse | 1 |
| 0 | 4 → 0 | toward 0: keep | 1 |
| 4 | 4 → 5 | away from 0: reverse | 2 |
| 5 | (none new) | 2 | |
| 1 | 1 → 3 | away from 0: reverse | 3 |
| 3 | 2 → 3 | toward 0: keep | 3 |
| 2 | (none new) | 3 |
Answer: 3.
Reorder Routes to Make All Paths Lead to the City Zero LeetCode Solution
Adjacency lists with a direction mark on each entry, then an iterative DFS from city 0. The C version keeps its lists in arrays.
Reorder Routes to Make All Paths Lead to the City Zero Code
1var minReorder = function(n, connections) {2 const graph = Array.from({ length: n }, () => []);3 for (const [a, b] of connections) {4 graph[a].push([b, 1]);5 graph[b].push([a, 0]);6 }7 const seen = new Array(n).fill(false);8 seen[0] = true;9 const stack = [0];10 let changes = 0;11 while (stack.length > 0) {12 const city = stack.pop();13 for (const [next, away] of graph[city]) {14 if (!seen[next]) {15 seen[next] = true;16 changes += away;17 stack.push(next);18 }19 }20 }21 return changes;22};
Reorder Routes to Make All Paths Lead to the City Zero in Python, Java, C++, TypeScript and C
Reorder Routes to Make All Paths Lead to the City Zero in Python
class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
graph = [[] for _ in range(n)]
for a, b in connections:
graph[a].append((b, 1))
graph[b].append((a, 0))
seen = [False] * n
seen[0] = True
stack = [0]
changes = 0
while stack:
city = stack.pop()
for nxt, away in graph[city]:
if not seen[nxt]:
seen[nxt] = True
changes += away
stack.append(nxt)
return changesReorder Routes to Make All Paths Lead to the City Zero in Java
class Solution {
public int minReorder(int n, int[][] connections) {
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] c : connections) {
graph.get(c[0]).add(new int[]{c[1], 1});
graph.get(c[1]).add(new int[]{c[0], 0});
}
boolean[] seen = new boolean[n];
seen[0] = true;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
int changes = 0;
while (!stack.isEmpty()) {
int city = stack.pop();
for (int[] edge : graph.get(city)) {
if (!seen[edge[0]]) {
seen[edge[0]] = true;
changes += edge[1];
stack.push(edge[0]);
}
}
}
return changes;
}
}Reorder Routes to Make All Paths Lead to the City Zero in C++
class Solution {
public:
int minReorder(int n, vector<vector<int>>& connections) {
vector<vector<pair<int, int>>> graph(n);
for (auto& c : connections) {
graph[c[0]].push_back({c[1], 1});
graph[c[1]].push_back({c[0], 0});
}
vector<bool> seen(n, false);
seen[0] = true;
vector<int> stack = {0};
int changes = 0;
while (!stack.empty()) {
int city = stack.back();
stack.pop_back();
for (auto [next, away] : graph[city]) {
if (!seen[next]) {
seen[next] = true;
changes += away;
stack.push_back(next);
}
}
}
return changes;
}
};Reorder Routes to Make All Paths Lead to the City Zero in TypeScript
function minReorder(n: number, connections: number[][]): number {
const graph: [number, number][][] = Array.from({ length: n }, () => []);
for (const [a, b] of connections) {
graph[a].push([b, 1]);
graph[b].push([a, 0]);
}
const seen: boolean[] = new Array(n).fill(false);
seen[0] = true;
const stack: number[] = [0];
let changes = 0;
while (stack.length > 0) {
const city = stack.pop()!;
for (const [next, away] of graph[city]) {
if (!seen[next]) {
seen[next] = true;
changes += away;
stack.push(next);
}
}
}
return changes;
}Reorder Routes to Make All Paths Lead to the City Zero in C
static int *head, *nxt, *to, *away, edges;
static void addRoad(int from, int target, int mark) {
to[edges] = target;
away[edges] = mark;
nxt[edges] = head[from];
head[from] = edges++;
}
int minReorder(int n, int** connections, int connectionsSize, int* connectionsColSize) {
head = malloc(n * sizeof(int));
nxt = malloc(2 * connectionsSize * sizeof(int));
to = malloc(2 * connectionsSize * sizeof(int));
away = malloc(2 * connectionsSize * sizeof(int));
edges = 0;
for (int i = 0; i < n; i++) {
head[i] = -1;
}
for (int i = 0; i < connectionsSize; i++) {
addRoad(connections[i][0], connections[i][1], 1);
addRoad(connections[i][1], connections[i][0], 0);
}
bool* seen = calloc(n, sizeof(bool));
int* stack = malloc(n * sizeof(int));
int top = 0, changes = 0;
seen[0] = true;
stack[top++] = 0;
while (top > 0) {
int city = stack[--top];
for (int e = head[city]; e != -1; e = nxt[e]) {
if (!seen[to[e]]) {
seen[to[e]] = true;
changes += away[e];
stack[top++] = to[e];
}
}
}
free(head);
free(nxt);
free(to);
free(away);
free(seen);
free(stack);
return changes;
}Edge Cases & Common Mistakes
- Searching only along road directions: roads pointing into 0 are never crossed from 0, so most of the tree is missed.
- Counting the wrong roads: count roads walked in their own direction (away from 0), not against it.
- Recursion depth: with up to 50,000 cities a chain makes a recursive DFS 50,000 calls deep; the stack-based version avoids that.
- Every road already correct: the answer is 0, as in a star with all roads pointing at 0.
Summary
Store each road in both directions with a mark for its real direction, DFS from city 0, and add up the marks of the roads walked in their own direction. O(n) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
